使用reflection对COM对象调用方法

我有一个COM对象的实例…它是这样创建的:

Type type = TypeDelegator.GetTypeFromProgID("Broker.Application"); Object application = Activator.CreateInstance(type); 

当我尝试调用方法时:

 type.GetMethod("RefreshAll").Invoke(application, null); 

– > type.GetMethod("RefreshAll")返回null 。 当我尝试使用type.GetMethods()获取所有方法时,只有以下方法:

  1. GetLifetimeService
  2. InitializeLifetimeService
  3. CreateObjRef
  4. 的ToString
  5. 等于
  6. GetHashCode的
  7. 的GetType

RefreshAll方法在哪里? 我怎么能调用呢?

您不能在COM对象上使用GetMethod,您必须使用不同的方式:

 this.application.GetType().InvokeMember("RefreshAll", BindingFlags.InvokeMethod, null, this.application, null); 

我在一个使用COM的旧项目中使用这种方式,所以它应该适合你。

我意识到这是一个迟到的答案,但是c#4通过引入dynamic关键字来改变一些东西,该关键字是在考虑COM-interop的情况下设计的。

MSDN:

C#团队专门针对C#4发行版的COM互操作场景是针对Microsoft Office应用程序(如Word和Excel)进行编程。 目的是使这个任务在C#中变得简单和自然,就像在Visual Basic中一样。 [1]

您的代码现在变为:

 Type type = TypeDelegator.GetTypeFromProgID("Broker.Application"); dynamic application = Activator.CreateInstance(type); application.RefreshAll(); // <---- new in c# 4 

现在,您不会在Visual Studio语句完成中看到RefreshAll() ,因此不要惊慌。 它会编译。

[1] 了解C#4中的动态关键字