使用反射与COM互操作(Using Reflection with COM Interop)

2019-06-26 11:50发布

一个互操作调用后,我得到一个COM对象。 我知道这个对象将是三种可能的COM类(1类,等级2,3类)之一,但不知道是哪一个在运行时。

一旦该对象的反射(interopObject.GetType())返回系统.__ ComObject的基RCW包装。

我需要的是在对象上设置一些属性 - 文本1,文本2,... Text30(实际名称,顺便说一句:)),它存在于所有三种类型。

所以,问题是,我可以以某种方式获取对象的运行时类型(这将解决我的问题,但可能是不可能的,因为.NET运行时可能没有这些信息),或者我可以设置一个COM对象的属性盲目地

这是我当前的代码,它失败:

for ( int i = 1; i <= 30; i++ )
{
  ProprertyInfo pi =interopObject.GetType().GetProperty("Text" +i.ToString()) 
  // this returns null for pi
  pi.GetSetMethod().Invoke(interopObject, new object[] { someValue });
}

由于马克,这三个走在我的永久收藏的噱头:

private static object LateGetValue(object obj, string propertyName)
{
  return RuntimeHelpers.GetObjectValue(NewLateBinding.LateGet(obj, null,
            propertyName, new object[0], null, null, null));
}

private static void LateSetValue(object obj, string propertyName, object value)
{
  NewLateBinding.LateSet(obj, null, propertyName, new []{value}, null, null);
}

private static void LateCallMethod(object obj, string methodName)
{
  NewLateBinding.LateCall(obj, null, methodName, new object[0], null,
            null, null, true);
}

Answer 1:

在C#4.0, dynamic将是理想的这种类型的鸭打字。

在此之前,我不知道如果VB.Net会更好,与Option Strict Off ,允许对后期绑定object

最坏的情况:在VB.Net写,然后使用反射镜为你;-p写C#

下面是一个例子,这需要对Microsoft.VisualBasic.dll中的引用,但在C#罚款:

public static object GetValue(object obj, string propertyName)
{
    return RuntimeHelpers.GetObjectValue(NewLateBinding.LateGet(obj, null,
         propertyName, new object[0], null, null, null));
}


文章来源: Using Reflection with COM Interop