Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling this[int index] via reflection

I try to implement a reflection-based late-bound library to Microsoft Office. The properties and methods of the Offce COM objects are called the following way:

Type type = Type.GetTypeFromProgID("Word.Application");
object comObject = Activator.CreateInstance(type);
type.InvokeMember(<METHOD NAME>, <BINDING FLAGS>, null, comObject, new object[] { <PARAMS>});

InvokeMember is the only possible way because Type.GetMethod / GetProperty works improperly with the COM objects.

Methods and properties can be called using InvokeMember but now I have to solve the following problem:

Method in the office-interop wrapper:

Excel.Workbooks wb = excel.Workbooks;
Excel.Workbook firstWb = wb[0];

respectively

foreach(Excel.Workbook w in excel.Workbooks)
  // doSmth. 

How can I call the this[int index] operator of Excel.Workbooks via reflection?

like image 200
tobias-kutter Avatar asked Oct 31 '12 11:10

tobias-kutter


1 Answers

I might have missunderstood your question, but hopefully this helps some.

This gets the n:th workbook when you have a workbook:

typeof(Workbooks).GetMethod("get_Item").Invoke(excel.Workbooks, new object[] { n });

GetMethod seems to work spendidly for me though, what version of .NET are you using?

Otherwise this might work:

typeof(Workbooks).InvokeMember("Item", BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty, null, excel.Workbooks, new object[] { n });

This one (Count) is also highly useful:

typeof(Workbooks).InvokeMember("Count", BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty, null, excel.Workbooks, null).

To get the workbooks if type is the excel type:

type.InvokeMember("Workbooks", BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty, null, excel.Workbooks, null)
like image 127
flindeberg Avatar answered Oct 11 '22 18:10

flindeberg