Type classType = typeof(SomeClass);
bool equal = Marshal.GenerateGuidForType(classType) == classType.GUID;
我还没有找到不符合这个条件的案例。
那么为什么以及何时我应该使用Marshal
方法而不是简单地获取GUID
属性?
最佳答案
... GenerateGuidForType provides the same functionality as the Type.GUID property.
所以根据文档,它们是相同的。但是,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.
}
}
}
关于c# - Marshal.GenerateGuidForType(Type) 和 Type.GUID 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4815096/