接口可以包含变量吗? [重复]

|                                                                                                                   这个问题已经在这里有了答案:                                                      
已邀请:
否。接口不能包含字段。 接口可以声明属性,但是它不提供该属性的任何实现,因此没有后备字段。仅当类实现接口时才需要后备字段(或自动属性)。     
接口可以是名称空间或类的成员,并且可以包含以下成员的签名:
Methods

Properties

Indexers

Events
可以在接口上声明属性。声明采用以下形式: 接口属性的访问器没有主体。 因此,访问器的目的是指示该属性是可读写,只读还是只写。 例:
// Interface Properties    
interface IEmployee
{
   string Name
   {
      get;
      set;
   }

   int Counter
   {
      get;
   }
}
实现方式:
public class Employee: IEmployee 
{
   public static int numberOfEmployees;

   private int counter;

   private string name;

   // Read-write instance property:
   public string Name
   {
      get
      {
         return name;
      }
      set
      {
         name = value;
      }
   }

   // Read-only instance property:
   public int Counter
   {    
      get    
      {    
         return counter;
      }    
   }

   // Constructor:
   public Employee()
   {
      counter = ++counter + numberOfEmployees;
   }
}  
主类:
public class MainClass
{
   public static void Main()
   {    
      Console.Write(\"Enter number of employees: \");

      string s = Console.ReadLine();

      Employee.numberOfEmployees = int.Parse(s);

      Employee e1 = new Employee();

      Console.Write(\"Enter the name of the new employee: \");

      e1.Name = Console.ReadLine();  

      Console.WriteLine(\"The employee information:\");

      Console.WriteLine(\"Employee number: {0}\", e1.Counter);

      Console.WriteLine(\"Employee name: {0}\", e1.Name);    
   }    
}
    
可以在接口上声明属性(未定义)。但是接口属性的访问者没有主体。因此,访问器的目的是指示该属性是可读写,只读还是只写。 如果您在此签出MSDN Doc,那么您会发现您没有在接口中定义属性,而是由继承的Class完成实现。
interface IEmployee
{
    string Name
    {
        get;
        set;
    }

    int Counter
    {
        get;
    }
}

public class Employee : IEmployee
{
    public static int numberOfEmployees;

    private string name;
    public string Name  // read-write instance property
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }

    private int counter;
    public int Counter  // read-only instance property
    {
        get
        {
            return counter;
        }
    }

    public Employee()  // constructor
    {
        counter = ++counter + numberOfEmployees;
    }
}
因此,在接口“ 5”中,属性的语法看起来像自动实​​现的属性,但它们只是指示该属性是“ 6”,“ 7”还是“ 8”,仅此而已。它的实现类的任务是执行实现并定义属性。     
不,这并不意味着。该接口实际上也不包含该属性。 请记住,接口必须由一个类实现才能使用。一个接口仅定义一个契约,这意味着实现该接口的任何类都将具有该接口定义的所有成员。该接口实际上没有那些成员;它更像是模板。实现该接口的类的实例是包含该属性的实例,因此是用于该属性的私有后备字段。 接口只能为以下成员定义签名: 方法 物产 索引器 大事记     
不,界面仅是“合约”。由实现类实现属性;它可能会或可能不会使用变量来支持它。     

要回复问题请先登录注册