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

标签 c# .net marshalling com-interop

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

我还没有找到不符合这个条件的案例。

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

最佳答案

参见 http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.generateguidfortype.aspx

... 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/

相关文章:

.net - 如何在 F# 中学习 GUI 编程

JSON Marshal uint 或 int 作为整数

c# - 如何实例化具有多个输入参数的泛型类型?

c# - 如何在 Windows Phone 上优化带有图像的长列表选择器的性能?

c# - 正则表达式在 c# 中不匹配

.Net HttpWebRequest/Response Cocoa 等效项

java - 适合新手的 Jaxb 编码

go - 如何序列化 [string]reflect.Value 类型的映射?

c# - 如何为流创建 TCP 消息帧

c# - C#中位的快速排列