C# 編程指南
介面屬性(C# 編程指南) 可以在介面(C# 參考)上聲明屬性。以下是介面索引器訪問器的樣本:C#複製代碼public interface ISampleInterface{ // Property declaration: string Name { get; set; }}介面屬性的訪問器不具有體。因此,訪問器的用途是指示屬性是否為讀寫、唯讀或唯寫。 樣本 在此例中,介面 IEmployee 具有讀寫屬性 Name 和唯讀屬性 Counter。Employee 類實現 IEmployee 介面並使用這兩種屬性。程式讀取新僱員的姓名和僱員的當前編號,並顯示僱員姓名和計算所得的僱員編號。可以使用屬性的完全限定名,它引用聲明成員的介面。例如:C#複製代碼string IEmployee.Name{ get { return"Employee Name"; } set { }}這被稱為明確介面實作(C# 編程指南)。例如,如果 Employee 類實現兩個介面 ICitizen 和 IEmployee,並且兩個介面都具有 Name 屬性,則需要顯式介面成員實現。即,如下屬性聲明:C#複製代碼string IEmployee.Name{ get { return"Employee Name"; } set { }}在 IEmployee 介面上實現 Name 屬性,而下面的聲明:C#複製代碼string ICitizen.Name{ get { return"Citizen Name"; } set { }}在 ICitizen 介面上實現 Name 屬性。C#複製代碼interface IEmployee{ string Name { get; set; } int Counter { get; }} publicclass Employee : IEmployee{ publicstaticint numberOfEmployees; privatestring name; publicstring Name // read-write instance property { get { return name; } set { name = value; } } privateint counter; publicint Counter // read-only instance property { get { return counter; } } public Employee() // constructor { counter = ++counter + numberOfEmployees; }} class TestEmployee{ staticvoid Main() { System.Console.Write("Enter number of employees: "); Employee.numberOfEmployees = int.Parse(System.Console.ReadLine()); Employee e1 = new Employee(); System.Console.Write("Enter the name of the new employee: "); e1.Name = System.Console.ReadLine(); System.Console.WriteLine("The employee information:"); System.Console.WriteLine("Employee number: {0}", e1.Counter); System.Console.WriteLine("Employee name: {0}", e1.Name); }}
輸入210Hazem Abolrous 樣本輸出 Enter number of employees: 210 Enter the name of the new employee: Hazem Abolrous The employee information: Employee number: 211 Employee name: Hazem Abolrous (來源:msdn )