2011-02-09 42 views
9

我沒有太多關於COM和coclasses的背景,所以我不太明白爲什麼我可以使用帶接口的new運算符。從語言/框架無關的觀點,它的迷惑,爲什麼這個編譯並運行正常:爲什麼可以創建一個COM接口的新實例?

using Microsoft.Office.Interop.Excel; 

public class ExcelProgram 
{ 
    static void Main(string[] args) 
    { 
     Application excel = new Application(); 
    } 
} 

在Visual Studio 2010中檢查Application顯示我:

using System.Runtime.InteropServices; 

namespace Microsoft.Office.Interop.Excel 
{ 
    // Summary: 
    //  Represents the entire Microsoft Excel application. 
    [Guid("000208D5-0000-0000-C000-000000000046")] 
    [CoClass(typeof(ApplicationClass))] 
    public interface Application : _Application, AppEvents_Event 
    { 
    } 
} 

這是怎麼回事幕後?

回答

5

這隻能用於COM接口,我相信。 Marc Gravell有一個解釋here

簡短的回答是一個COM接口可以與一個「默認」實現類配對,這樣當你「實例化」接口時,你實際上正在創建一個默認實現類的實例。在您示例中的Application接口的情況下,該接口似乎是ApplicationClass

+0

謝謝。該鏈接有鏈接到http://stackoverflow.com/questions/1093536/how-does-the-c-compiler-detect-com-types。猜猜我在搜索錯誤的關鍵字 - 看起來像我的問題本質上是重複的。 – ide 2011-02-09 23:43:50

相關問題