Type classType = typeof(SomeClass);
bool equal = Marshal.GenerateGuidForType(classType) == classType.GUID;
我还没有找到失败这种情况的情况。Marshal.GenerateGuidForType(Type)和Type.GUID有什么区别?
因此为什么和什么时候我应该使用Marshal
方法而不是简单地获取GUID
属性?
Type classType = typeof(SomeClass);
bool equal = Marshal.GenerateGuidForType(classType) == classType.GUID;
我还没有找到失败这种情况的情况。Marshal.GenerateGuidForType(Type)和Type.GUID有什么区别?
因此为什么和什么时候我应该使用Marshal
方法而不是简单地获取GUID
属性?
... GenerateGuidForType提供相同的功能的Type.GUID财产。
所以根据文档他们是一样的。但是,Marshal.GenerateGuidForType仅适用于RuntimeType对象,而Type.GUID也适用于其他类型的实现。
例如为:
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属性”相同的功能。使用最适合你的应该是安全的。