使用Ref对COM对象调用方法

Pra*_*abu 7 c# com reflection

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

Type type = TypeDelegator.GetTypeFromProgID("Broker.Application");
Object application = Activator.CreateInstance(type);
Run Code Online (Sandbox Code Playgroud)

当我尝试调用方法时:

type.GetMethod("RefreshAll").Invoke(application, null);
Run Code Online (Sandbox Code Playgroud)

- > type.GetMethod("RefreshAll")退货null.当我尝试使用所有方法时type.GetMethods(),只有这些方法:

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

RefreshAll方法在哪里?我该如何调用它?

Nat*_*n W 12

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

this.application.GetType().InvokeMember("RefreshAll", BindingFlags.InvokeMethod, null, this.application, null);
Run Code Online (Sandbox Code Playgroud)

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


Mic*_*kyD 5

我意识到这是一个迟到的答案,但是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
Run Code Online (Sandbox Code Playgroud)

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

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