开发者

Creating instance of interface in C#

开发者 https://www.devze.com 2022-12-23 07:26 出处:网络
I\'m working with MS Excel interop in C# and I don\'t understand how this particular line of code works:

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.I开发者_开发技巧nterop.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?


Ayende blogged about this.


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

精彩评论

暂无评论...
验证码 换一张
取 消