接口属性

定义带索引器和访问器的接口

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

由于接口本身特点,接口属性的访问器不具有体。因此,访问器的用途是指示属性是否为读写、只读或只写。

在此例中,接口 IEmployee 具有读写属性 Name 和只读属性 CounterEmployee 类实现 IEmployee 接口并使用这两种属性。程序读取新雇员的姓名和雇员的当前编号,并显示雇员姓名和计算所得的雇员编号。

可以使用属性的完全限定名,它引用声明成员的接口。例如:

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

这被称为显式接口实现

如果 Employee 类实现两个接口 ICitizen 和 IEmployee,并且两个接口都具有 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);
    }
}

 

posted @ 2013-01-10 14:47  xiepeixing  阅读(2693)  评论(0编辑  收藏  举报