接口属性(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#
复制代码
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 ;
    }
}
 
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
 (来源:msdn )
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值