What's the difference between Marshal.GenerateGuidForType(Type) and Type.GUID?

丶灬走出姿态 提交于 2019-12-10 04:31:07

问题


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

I haven't found a case that fail this condition.

So why and when should I use the Marshal method instead of simply getting the GUID property?


回答1:


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

... GenerateGuidForType provides the same functionality as the Type.GUID property.

So according to documentation they are the same. However, Marshal.GenerateGuidForType works only for RuntimeType objects, while Type.GUID is provided for some other Type implementations as well.

E.g.:


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




回答2:


According to MSDN, "GenerateGuidForType provides the same functionality as the Type.GUID property". It should be safe to use the one that suits you the best.



来源:https://stackoverflow.com/questions/4815096/whats-the-difference-between-marshal-generateguidfortypetype-and-type-guid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!