此例说明了实例、静态和只读属性。它从键盘接受雇员的姓名,按 1 递增 NumberOfEmployees,并显示雇员的姓名和编号。
class Program
{
static void Main(string[] args)
{
Employee.NumberOffEmployees = 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);
Console.ReadLine();
}
}
public class Employee
{
public static int NumberOffEmployees;
private static int counter;
private string name;
public string Name
{
get{return name;}
set{name=value;}
}
public static int Counter
{
get{return counter;}
}
public Employee()
{
counter=++counter+NumberOffEmployees;
}
}
{
static void Main(string[] args)
{
Employee.NumberOffEmployees = 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);
Console.ReadLine();
}
}
public class Employee
{
public static int NumberOffEmployees;
private static int counter;
private string name;
public string Name
{
get{return name;}
set{name=value;}
}
public static int Counter
{
get{return counter;}
}
public Employee()
{
counter=++counter+NumberOffEmployees;
}
}
输出:Employee number: 101
Employee name: Claude Vige
Employee name: Claude Vige
2.此例说明如何访问基类中被派生类中具有同一名称的另一个属性隐藏的属性。
class Program
{
static void Main(string[] args)
{
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);
Console.ReadLine();
}
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"; }
}
}
}
{
static void Main(string[] args)
{
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);
Console.ReadLine();
}
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"; }
}
}
}
输出:Name in the derived class is: John, Manager
Name in the base class is: Mary
Name in the base class is: Mary