Creating instance of interface in C#

后端 未结 3 1444
暖寄归人
暖寄归人 2021-01-05 21:28

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.Appli         


        
3条回答
  •  没有蜡笔的小新
    2021-01-05 22:11

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

提交回复
热议问题