如何获取COM对象的类型

时间:2009-09-15 20:51:04

标签: .net reflection com interop com-interop

我在Visual Studio中引用了一个COM库,因此它为我自动创建了相应的Interop程序集。我想对这些com对象执行GetType(),但它们总是返回System.__ComObject。查询它们的接口有效:

bool isOfType = someComeObject is ISomeComObject; //this works

但我真正想要的是返回com对象的实际类型:

Type type = someComeObject.GetType(); //returns System.__ComObject :-(

有谁知道怎么做我想做的事?

4 个答案:

答案 0 :(得分:48)

添加对Microsoft.VisualBasic.dll的引用,然后:

Microsoft.VisualBasic.Information.TypeName(someCOMObject)

MSDN参考here

答案 1 :(得分:5)

Darin接受的答案需要依赖Microsoft.VisualBasic.dll。如果你不想拥有它,你可以使用这个简单的助手类:

public static class TypeInformation
{
    public static string GetTypeName(object comObject)
    {
        var dispatch = comObject as IDispatch;

        if (dispatch == null)
        {
            return null;
        }

        var pTypeInfo = dispatch.GetTypeInfo(0, 1033);

        string pBstrName;
        string pBstrDocString;
        int pdwHelpContext;
        string pBstrHelpFile;
        pTypeInfo.GetDocumentation(
            -1, 
            out pBstrName, 
            out pBstrDocString, 
            out pdwHelpContext, 
            out pBstrHelpFile);

        string str = pBstrName;
        if (str[0] == 95)
        {
            // remove leading '_'
            str = str.Substring(1);
        }

        return str;
    }

    [ComImport]
    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("00020400-0000-0000-C000-000000000046")]
    private interface IDispatch
    {
        int GetTypeInfoCount();

        [return: MarshalAs(UnmanagedType.Interface)]
        ITypeInfo GetTypeInfo(
            [In, MarshalAs(UnmanagedType.U4)] int iTInfo,
            [In, MarshalAs(UnmanagedType.U4)] int lcid);

        void GetIDsOfNames(
            [In] ref Guid riid,
            [In, MarshalAs(UnmanagedType.LPArray)] string[] rgszNames,
            [In, MarshalAs(UnmanagedType.U4)] int cNames,
            [In, MarshalAs(UnmanagedType.U4)] int lcid,
            [Out, MarshalAs(UnmanagedType.LPArray)] int[] rgDispId);
    }
}

答案 2 :(得分:1)

你基本上已经明白了。 COM对象上的GetType()将为您提供System .__ ComObject,您必须尝试将其强制转换为其他内容以查看对象的实际内容。

答案 3 :(得分:-1)

几天前,当我在寻找System.__ComObject对象的完整类型名称时,我偶然发现了这个问题。我最终使用Darin的解决方案获取了类型名称,然后遍历所有程序集中的所有类来测试匹配:

    typeName = Microsoft.VisualBasic.Information.TypeName(someCOMObject);
    foreach (System.Reflection.Assembly assembly in AppDomain.CurrentDomain.GetAssemblies())
    { 
        foreach (Type type in assembly.GetTypes())
        {
            if ((someCOMObject as type)!=null)
                fullTypeName = type.FullName;
        }
    }

不是最快最优雅的解决方案,但它确实有效。