介面屬性 (C# 程式設計手冊)

屬性可以在 interface (C# 參考) 上宣告, 下列是介面索引子存取子的範例:

public interface ISampleInterface
{
    // Property declaration:
    string Name
    {
        get;
        set;
    }
}

介面屬性的存取子沒有主體, 因此,存取子的目的是指示屬性是讀寫、唯讀或唯寫。

範例

在這個範例裡,IEmployee 介面有 Name 讀寫屬性和 Counter 唯讀屬性。 Employee 類別實作 IEmployee 介面,並且使用這兩個屬性。 程式讀取新員工的名稱和員工的目前編號,並顯示員工名稱和計算過的員工編號。

您可以使用屬性的完整名稱,這個屬性會參考成員宣告的介面。 例如:

string IEmployee.Name
{
    get { return "Employee Name"; }
    set { }
}

這稱為明確介面實作 (C# 程式設計手冊)。 例如,如果 Employee 類別實作 ICitizen 和 IEmployee 這兩個介面,而且兩個介面都有 Name 屬性,則將會需要明確介面成員實作, 即如下的屬性宣告:

string IEmployee.Name
{
    get { return "Employee Name"; }
    set { }
}

在 IEmployee 介面上實作 Name 屬性,在下列宣告時:

string ICitizen.Name
{
    get { return "Citizen Name"; }
    set { }
}

在 ICitizen 介面上實作 Name 屬性。

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;
    }
}

class TestEmployee
{
    static void 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);
    }
}
  210
Hazem 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

請參閱

參考

屬性 (C# 程式設計手冊)

使用屬性 (C# 程式設計手冊)

屬性與索引子之間的比較 (C# 程式設計手冊)

索引子 (C# 程式設計手冊)

介面 (C# 程式設計手冊)

概念

C# 程式設計手冊