C# 按PIA接口类型获取CLSID

C# 按PIA接口类型获取CLSID,c#,com,C#,Com,编辑:看起来Jon Skeet有一些类似的问题: 如何在主互操作程序集中获取给定接口的CLSID?下面是我要说的: // The c# compiler does some interesting magic. // The following code ... var app = new Microsoft.Office.Interop.Outlook.Application(); // ... is compiled like so (disassembled with Reflecto

编辑:看起来Jon Skeet有一些类似的问题:

如何在主互操作程序集中获取给定接口的CLSID?下面是我要说的:

// The c# compiler does some interesting magic.
// The following code ...
var app = new Microsoft.Office.Interop.Outlook.Application();

// ... is compiled like so (disassembled with Reflector):
var app =((Microsoft.Office.Interop.Outlook.Application)
  Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("0006F03A-0000-0000-C000-000000000046"))));

Microsoft.Office.Interop.Outlook.Application是一个接口,因此无法直接实例化。这里有趣的是,c#允许您将这些COM接口视为可以使用
new
关键字实例化的类

我想知道的是,给定给定接口的
System.Type
,如何获取CLSID


注意:我最终希望能够根据接口的
系统创建一个实例。键入
-我不在乎如何创建。我在这里假设,最简单的方法是获得给定类型的CLSID,就像c编译器一样。

尝试该属性。

以下是我当前的解决方案:

// Get the PIA assemby name, using the GUID of the typlib
string asmName;
string asmCodeBase;
var conv = new System.Runtime.InteropServices.TypeLibConverter();
conv.GetPrimaryInteropAssembly(new Guid("00062FFF-0000-0000-C000-000000000046"), 9, 3, 0, out asmName, out asmCodeBase);

// Load the PIA, and get the interface type
var assembly = System.Reflection.Assembly.Load(asmName);
var type = assembly.GetType("Microsoft.Office.Interop.Outlook.Application");

// Get the coclass
var coClassAttr = (System.Runtime.InteropServices.CoClassAttribute)
    type.GetCustomAttributes(typeof(System.Runtime.InteropServices.CoClassAttribute), false)[0];
var coClass = coClassAttr.CoClass;

// Instantiate the coclass
var app = Activator.CreateInstance(coClassAttr.CoClass);

// If needed, the CLSID is also available:
var clsid = coClass.GUID;
我通过拆开GAC的PIA找到了答案。我注意到,
Outlook.Application
用一个
CoClassAttribute
装饰,如下所示:

[ComImport, Guid("00063001-0000-0000-C000-000000000046"), CoClass(typeof(ApplicationClass))]
public interface Application : _Application, ApplicationEvents_11_Event
{
}
ApplicationClass
看起来像:

[ComImport, ClassInterface((short) 0), ComSourceInterfaces("Microsoft.Office.Interop.Outlook.ApplicationEvents_11\0Microsoft.Office.Interop.Outlook.ApplicationEvents\0Microsoft.Office.Interop.Outlook.ApplicationEvents_10\0"), Guid("0006F03A-0000-0000-C000-000000000046"), TypeLibType((short) 11)]
public class ApplicationClass : _Application, Application, ApplicationEvents_11_Event, ApplicationEvents_Event, ApplicationEvents_10_Event
{
    //...
}

让我知道你们的想法,这样我就可以决定是否将此标记为所选答案。

我尝试过,但没有给出正确的GUID,如下所示:
typeof(Outlook.Application).GUID!=键入.GetTypeFromCLSID(新Guid(“0006F03A-0000-0000-C000-0000000000 46”)).Guid