2010-05-05 46 views
7

反思我有一個COM對象......這是這樣創造的一個實例:Invoke方法使用的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. 的Equals
  6. 的GetHashCode
  7. 的GetType

RefreshAll方法在哪裏?我該如何援引它?

回答

12

不能對COM對象使用GetMethod,你必須使用一個不同的 方式:

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

我使用這種方式在使用COM所以它應該工作正常爲你的老項目。

+1

雖然在當時的罰款答案,C#4使得它更容易下面 – MickyD 2015-02-07 00:12:41

+1

注意通過'dynamic'關鍵字進行COM-互操作,從我的工具HTTPS使用'dynamic'未來://github.com/awaescher/RepoZ我發現它有很多內存泄漏。我轉向Nathan W的答案來解決這個問題!在這裏看到更多:https://stackoverflow.com/questions/33080252/memory-overflow-having-an-increasing-number-of-microsoft-csharp-runtimebinder-s/34123315 – Waescher 2017-08-22 12:26:45

+0

請參閱其他意見MickyD的答案如何處理這個問題... – Waescher 2017-08-22 21:32:33

4

我意識到這是一個遲到的答案,但c#4改變了一些問題,引入了設計了COM-interop的dynamic關鍵字。

MSDN:是,在C#4發佈專門針對C#的團隊對編程Microsoft Office應用程序,如Word和Excel

的COM互操作場景。目的是使這個任務在C#中像在Visual Basic中一樣簡單自然。 [1]

現在您的代碼變成:

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

現在,你將不會看到RefreshAll()在Visual Studio語句完成,所以不要驚慌。它會編譯。

[1] Understanding the Dynamic Keyword in C# 4

+1

注意,來自使用'動態'在我的工具https://github.com/awaescher/RepoZ我發現它有沉重的內存泄漏。我轉向Nathan W的答案來解決這個問題!查看更多這裏:https:// stackoverflow。com/questions/33080252/memory-overflow-having-an-increasing-number-of-microsoft-csharp-runtimebinder -s/34123315 – Waescher 2017-08-22 12:26:28

+0

@Waescher odd考慮到MS首先將其用於COM。我懷疑你只是沒有正確地發佈與**無關的東西** – MickyD 2017-08-22 12:36:46

+0

@Waescher ooh我只是做了一些Google搜索,看起來你是正確的。討厭的小**動態**。好找 – MickyD 2017-08-22 12:52:05