在Interop调用之后,我会得到一个COM对象。我知道这个对象将是三个可能的COM类(Class1、Class2、Class3)中的一个,但在运行时不知道它是哪一个。
对该对象进行反射 (interopObject.GetType()),返回System.__ComObject的基本RCW包装器。
我需要的是在对象上设置一些属性 - Text1、Text2、... 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 });
}
感谢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);
}