使用反射与COM互操作 [英] Using Reflection with COM Interop
问题描述
在互操作调用之后,我回到一个COM对象。
我知道这个对象将是三个可能的COM类之一(Class1,Class2,Class3),但不知道在运行时是哪一个。
After an interop call, I get back a COM object. I know this object will be one of three possible COM classes (Class1, Class2, Class3), but do not know which one in runtime.
对象(interopObject.GetType())返回System .__ ComObject的基本RCW包装器。
The reflection upon that object (interopObject.GetType()) returns the base RCW wrapper of System.__ComObject.
我需要的是在对象上设置一些属性 - Text1,Text2 ,... Text30(actual names,btw :)),它存在于所有三个类中。
What I need is to set some properties on the object - Text1, Text2, ... Text30 (actual names, btw :)), which exist in all three classes.
所以,问题是,我能以某种方式获得运行时类型对象(这将解决我的问题,但可能是不可能的,因为.net运行时可能没有这个信息),或者我可以设置一个COM对象的属性盲目
So, the question is, can I somehow get the runtime type of the object (this would solve my problem, but might be impossible, as the .net runtime might not have that info), or can I set a property of a COM object blindly
这是我当前的代码,它失败:
this is my current code, which fails:
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 });
}
三个在我永久的g头集合:
Thanks to Marc, these three go in my permanent gimmicks collection:
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);
}
推荐答案
在这之前,我想知道VB.Net是否会更好, Option Strict Off
允许后期绑定对象
。
Until then, I wonder if VB.Net would be better, with Option Strict Off
to allow late binding against object
.
最差的情况:在VB.Net中写,然后使用反射器为你编写C#;-p
Worst case: write it in VB.Net, then use reflector to write the C# for you ;-p
这里有一个例子, .VisualBasic.dll,但在C#中很好:
Here's an example, that requires a reference to Microsoft.VisualBasic.dll, but is fine in C#:
public static object GetValue(object obj, string propertyName)
{
return RuntimeHelpers.GetObjectValue(NewLateBinding.LateGet(obj, null,
propertyName, new object[0], null, null, null));
}
这篇关于使用反射与COM互操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!