繁体   English   中英

使用Ref对COM对象调用方法

[英]Invoke method using Reflection on COM Object

我有一个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中的动态关键字

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM