Using Reflection with COM Interop

After calling interop, I return a COM object. I know that this object will be one of the three possible COM classes (Class1, Class2, Class3), but I don’t know which one is executed at runtime.

Reflection on this object (interopObject.GetType ()) returns the base RCW wrapper of System .__ ComObject.

I need to set some object properties - Text1, Text2, ... Text30 (actual names, btw :)) that exist in all three classes.

So the question is, can I somehow get the runtime type of the object (this will solve my problem, but it may not be possible, since the .net runtime may not have this information), or I can set the COM object property blindly

this is my current code that doesn't work:

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

Thanks to Mark, these three are in my collection of constant tricks:

 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); } 
+3
source share
1 answer

In C # 4.0, dynamic ideal for this type of duck input.

Until then, I am wondering if VB.Net would be better with Option Strict Off to allow late binding to object .

In the worst case: write it to VB.Net, then use a reflector to write C # for you; -p

Here is an example that requires a link to Microsoft.VisualBasic.dll, but in C # this is fine:

 public static object GetValue(object obj, string propertyName) { return RuntimeHelpers.GetObjectValue(NewLateBinding.LateGet(obj, null, propertyName, new object[0], null, null, null)); } 
+7
source

Source: https://habr.com/ru/post/1380003/


All Articles