c# - 通过反射调用 this[int index]

标签 c# reflection office-interop

我尝试为 Microsoft Office 实现一个基于反射的后期绑定(bind)库。 Office COM 对象的属性和方法调用方式如下:

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

InvokeMember 是唯一可能的方法,因为 Type.GetMethod/GetProperty 无法正确处理 COM 对象。

可以使用 InvokeMember 调用方法和属性,但现在我必须解决以下问题:

office-interop 包装器中的方法:

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

分别

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

如何通过反射调用Excel.Workbooks的this[int index]操作符?

最佳答案

我可能误解了你的问题,但希望这对一些人有所帮助。

当您有一个工作簿时,这将获取第 n:th 个工作簿:

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

GetMethod 对我来说似乎很有效,您使用的是什么版本的 .NET?

否则这可能会起作用:

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

这个(计数)也非常有用:

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

如果类型是 excel 类型,则获取工作簿:

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

关于c# - 通过反射调用 this[int index],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13156620/

相关文章:

C#运行临时存储过程

c# - 哈希表中的列表丢失所有条目

c# - InvokeMethod 可以用作可选参数吗?

C# 互操作字、剪切和粘贴适用于 Office 2016,但不适用于 Office 2019

c# - 如何使用 C# 删除 word 文档的只读属性?

C# 将周作为 DateTime 返回

c# - UIImagePickerController' 不包含 'DismissModalViewControllerAnimated' Xamarin iOS 的定义

javascript - Javascript 可以获取文本形式的函数吗?

Java - 创建以字符串为名称的类的实例

c# - ppt保存幻灯片时保留源模板