导航

属性 get set

Posted on 2011-04-08 19:59  beeone  阅读(1123)  评论(0编辑  收藏  举报
此例说明了实例、静态和只读属性。它从键盘接受雇员的姓名,按 1 递增 NumberOfEmployees,并显示雇员的姓名和编号。
public class Employee
{
public static int NumberOfEmployees;
private static int counter;
private string name;

// A read-write instance property:
public string Name
{
get { return name; }
set { name = value; }
}

// A read-only static property:
public static int Counter
{
get { return counter; }
}

// A Constructor:
public Employee()
{
// Calculate the employee's number:
counter = ++counter + NumberOfEmployees;
}
}

class TestEmployee
{
static void Main()
{
Employee.NumberOfEmployees
= 100;
Employee e1
= new Employee();
e1.Name
= "Claude Vige";

System.Console.WriteLine(
"Employee number: {0}", Employee.Counter);
System.Console.WriteLine(
"Employee name: {0}", e1.Name);
}
}



Employee number:
101

Employee name: Claude Vige


此例说明如何访问基类中被派生类中具有同一名称的另一个属性隐藏的属性。


public class Employee
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}

public class Manager : Employee
{
private string name;

// Notice the use of the new modifier:
public new string Name
{
get { return name; }
set { name = value + ", Manager"; }
}
}

class TestHiding
{
static void Main()
{
Manager m1
= new Manager();

// Derived class property.
m1.Name = "John";

// Base class property.
((Employee)m1).Name = "Mary";

System.Console.WriteLine(
"Name in the derived class is: {0}", m1.Name);
System.Console.WriteLine(
"Name in the base class is: {0}", ((Employee)m1).Name);
}
}




Name
in the derived class is: John, Manager

Name
in the base class is: Mary