使用COM Interopreflection

在互操作之后,我找回了一个COM对象。 我知道这个对象将是三个可能的COM类之一(Class1,Class2,Class3),但不知道哪个在运行时。

对该对象的reflection(interopObject.GetType())返回System .__ ComObject的基本RCW包装器。

我需要的是在对象上设置一些属性 – Text1,Text2,… Text30(实际名称,btw :)),它们存在于所有三个类中。

所以,问题是,我可以以某种方式获取对象的运行时类型(这将解决我的问题,但可能是不可能的,因为.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 }); } 

感谢Marc,这三个进入我的永久噱头系列:

 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); } 

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

在那之前,我想知道VB.Net是否会更好, Option Strict Off允许后期绑定object

最坏的情况:在VB.Net中编写它,然后使用reflection器为你编写C#;-p

这是一个示例,需要引用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)); }