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