Csharp/C#教程:Marshal.GenerateGuidForType(Type)和Type.GUID之间有什么区别?分享


Marshal.GenerateGuidForType(Type)和Type.GUID之间有什么区别?

Type classType = typeof(SomeClass); bool equal = Marshal.GenerateGuidForType(classType) == classType.GUID; 

我没有找到一个失败的情况。

那么为什么以及何时应该使用Marshal方法而不是简单地获取GUID属性?

请参阅https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.generateguidfortype.aspx

… GenerateGuidForType提供与Type.GUID属性相同的function。

所以根据文档他们是一样的。 但是,Marshal.GenerateGuidForType仅适用于RuntimeType对象,而Type.GUID也适用于其他一些Type实现。

例如:

 using System; using System.CodeDom; using System.Runtime.InteropServices; using System.Workflow.ComponentModel.Compiler; namespace Samples { class Program { static CodeCompileUnit BuildHelloWorldGraph() { var compileUnit = new CodeCompileUnit(); var samples = new CodeNamespace("Samples"); compileUnit.Namespaces.Add(samples); var class1 = new CodeTypeDeclaration("Class1"); samples.Types.Add(class1); return compileUnit; } static void Main(string[] args) { var unit = BuildHelloWorldGraph(); var typeProvider = new TypeProvider(null); typeProvider.AddCodeCompileUnit(unit); var t = typeProvider.GetType("Samples.Class1"); Console.WriteLine(t.GUID); // prints GUID for design time type instance. Console.WriteLine(Marshal.GenerateGuidForType(t)); // throws ArgumentException. } } } using System; using System.CodeDom; using System.Runtime.InteropServices; using System.Workflow.ComponentModel.Compiler; namespace Samples { class Program { static CodeCompileUnit BuildHelloWorldGraph() { var compileUnit = new CodeCompileUnit(); var samples = new CodeNamespace("Samples"); compileUnit.Namespaces.Add(samples); var class1 = new CodeTypeDeclaration("Class1"); samples.Types.Add(class1); return compileUnit; } static void Main(string[] args) { var unit = BuildHelloWorldGraph(); var typeProvider = new TypeProvider(null); typeProvider.AddCodeCompileUnit(unit); var t = typeProvider.GetType("Samples.Class1"); Console.WriteLine(t.GUID); // prints GUID for design time type instance. Console.WriteLine(Marshal.GenerateGuidForType(t)); // throws ArgumentException. } } } 

根据MSDN , “GenerateGuidForType提供与Type.GUID属性相同的function” 。 使用最适合你的那种应该是安全的。

上述就是C#学习教程:Marshal.GenerateGuidForType(Type)和Type.GUID之间有什么区别?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1038955.html

(0)
上一篇 2022年1月26日
下一篇 2022年1月26日

精彩推荐