接口可以包含变量吗?

San*_*eep 35 .net c# oop properties interface

可能重复:
为什么C#接口不能包含字段?

大家好,

Jon Skeet回答了一个问题,即使用属性是由变量支持的.

但是C#中允许接口中的属性.这是否意味着C#中的接口可以包含一个变量,该属性支持的变量将如何处理?

提前致谢.

And*_*per 26

不可以.接口不能包含字段.

接口可以声明一个Property,但它不提供任何实现,因此没有后备字段.只有在类实现接口时才需要支持字段(或自动属性).

  • @Sandeep - 字段没有 get/set 方法。字段只是与类关联的存储项。属性是在客户端代码中像字段一样访问的成员,但允许执行代码以确定要返回的值,或在设置值时进行一些处理。一个属性可能与一个或多个字段相关联,但并非必须如此。自动属性 ​​(`int Property { get; set; }`) 是用于获取和设置私有支持字段的属性的语法糖。 (3认同)

Abh*_*bhi 24

接口可以是命名空间或类的成员,并且可以包含以下成员的签名:

Methods

Properties

Indexers

Events
Run Code Online (Sandbox Code Playgroud)

可以在接口上声明属性.声明采用以下形式:接口属性的访问者没有正文.

因此,访问器的目的是指示属性是读写,只读还是只写.

例:

// Interface Properties    
interface IEmployee
{
   string Name
   {
      get;
      set;
   }

   int Counter
   {
      get;
   }
}
Run Code Online (Sandbox Code Playgroud)

执行:

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;
   }
}  
Run Code Online (Sandbox Code Playgroud)

MainClass:

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);    
   }    
}
Run Code Online (Sandbox Code Playgroud)


She*_*Pro 5

属性可以在接口上声明(未定义)。但是接口属性的访问器没有主体。因此,访问器的目的指示该属性是读写、只读还是只写。

如果你查看MSDN 文档,你会发现你没有在接口中定义属性,而是由继承类完成实现。

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,在接口中,IEmployee属性的语法看起来像自动实​​现的属性,但它们只是指示属性是否是read-writeread-only、 或write-only,仅此而已。实现类的任务是执行实现并定义属性。