In C#, the interface can be instantiated?

前端 未结 7 1909
孤街浪徒
孤街浪徒 2021-01-20 21:29

I\'m reading the code in here. I find that private ITreeModel _model; in TreeList.cs:

namespace Aga.Controls.Tree
{
    public class TreeList: L         


        
7条回答
  •  离开以前
    2021-01-20 21:44

    You can never instantiate an interface in C# directly, but yes you can instantiate a subclass implementing that interface. For example:

    interface IShape
    {
       //Method Signature
       void area(int r);
    }
    
    public class Circle : IShape
    {
       //method Implementation
       void area(int r)
       {
          float area;
          area = 3.14 * r * r;
          Console.WriteLine("The area of the circle is: {0}",area);
       }
    }
    
    public class Shapes
    {
       public static void Main() {
          //Uncommenting the following line will cause compiler error as the  
          // line tries to create an instance of interface.
          // interface i = new IShape();
    
         // We can have references of interface type.
         IShape i = new Circle();
         i.area(10);
       }
    }
    

提交回复
热议问题