在互操作之后,我找回了一个COM对象。 我知道这个对象将是三个可能的COM类之一(Class1,Class2,Class3),但不知道哪个在运行时。
对该对象的反射(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);
}
答案 0 :(得分:8)
在C#4.0中,dynamic
非常适合这种类型的鸭子打字。
在此之前,我想知道VB.Net是否会更好,Option Strict Off
允许后期绑定object
。
最坏的情况:在VB.Net中编写,然后使用反射器为你编写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));
}