65.9K
CodeProject 正在变化。 阅读更多。
Home

获取 COM 对象实现的所有类型

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.75/5 (4投票s)

2009年2月17日

公共领域
viewsIcon

27834

downloadIcon

281

如何返回 COM 对象实现的所有类型。

引言

本文展示了如何获取 COM 对象实现的所有类型。

背景

在 C# 中获取 COM 对象时,如果您知道它实现的类和接口,就可以轻松地将其转换为所需的类型。但是,如果您不知道它的类型,或者更确切地说,您认为您知道它的类型,但它实际上并没有实现该类型,该怎么办?

使用代码

以下方法将返回 COM 对象实现的所有类型。我不在生产代码中使用它,但我在编写代码时偶尔会使用它。

/// <summary>
/// Get all implemented types in a COM object. Code based on work at
/// http://fernandof.wordpress.com/2008/02/05/how-to-check-
///          the-type-of-a-com-object-system__comobject-with-visual-c-net/
/// </summary>
/// <param name="comObject">The object we want all types of.</param>
/// <param name="assType">Any type in the COM assembly.</param>
/// <returns>All implemented classes/interfaces.</returns>
public static Type[] GetAllTypes(object comObject, Type assType)
{

    // get the com object and fetch its IUnknown
    IntPtr iunkwn = Marshal.GetIUnknownForObject(comObject);

    // enum all the types defined in the interop assembly
    Assembly interopAss = Assembly.GetAssembly(assType);
    Type[] excelTypes = interopAss.GetTypes();

    // find all types it implements
    ArrayList implTypes = new ArrayList();
    foreach (Type currType in excelTypes)
    {
        // com interop type must be an interface with valid iid
        Guid iid = currType.GUID;
        if (!currType.IsInterface || iid == Guid.Empty)
        continue;

        // query supportability of current interface on object
        IntPtr ipointer;
        Marshal.QueryInterface(iunkwn, ref iid, out ipointer);

        if (ipointer != IntPtr.Zero)
          implTypes.Add(currType);

        }

    // no implemented type found
    return (Type[])implTypes.ToArray(typeof(Type));
}

历史

原始帖子。

© . All rights reserved.