简体   繁体   中英

Creating instance of interface in C#

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?

艾恩德在博客中写到这一点。

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?

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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