【发布时间】:2010-11-12 19:09:10
【问题描述】:
在互操作调用之后,我得到了一个 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);
}
【问题讨论】:
标签: c# reflection com interop