Creating instance of interface in C#

2019-02-14 07:23发布

I'm working with MS Excel interop in C# and I don't understand how this particular line of code works:

var excel = new Microsoft.Office.Interop.Excel.Application();

where Microsoft.Office.Interop.Excel.Application is an INTERFACE defined as:

[Guid("000208D5-0000-0000-C000-000000000046")]
[CoClass(typeof(ApplicationClass))]
public interface Application : _Application, AppEvents_Event
{
}

I'm thinking that some magic happens when the interface is decorated with a CoClass attribute, but still how is it possible that we can create an instance of an interface with a new keyword? Shouldn't it generate a compile time error?

标签: c# oop
3条回答
Bombasti
2楼-- · 2019-02-14 08:05

Ayende blogged about this.

查看更多
祖国的老花朵
3楼-- · 2019-02-14 08:10

ApplicationClass is implement Application interface. In two words, interface is declaration of methods of class. Your line of code create instance of class ApplicationClass (because interface have attribute with class with constructor), query this instance of interface Application and put this to variable excel.

On second question: no, you can't create interface with 'new' keyword. Because, any interface have only declaration of methods, not implementation. You can try this for creating you own classes and interfaces:

interface MyIntf {
   void method1(string s1);
}

public class MyIntfImplementation : MyIntf {

   void method1(string s1) {
     // do it something
   }
}

After this you can use this:

MyIntf q = new MyIntfImplementation();
q.method1();
查看更多
何必那么认真
4楼-- · 2019-02-14 08:17

Actually code that you mentioned created instance of the ApplicationClass class and that is what CoClass attribute does.

See this answer for details: How does the C# compiler detect COM types?

查看更多
登录 后发表回答