不能通过实例引用静态成员,只可以通过类型名称引用静态成员。
下面是一个msdn上的例子:
假设该类包含一种对雇员计数的方法和一个存储雇员数的字段。该方法和字段都不属于任何实例雇员,而是属于公司类。因此,应该将它们声明为此类的静态成员。
// cs_static_keyword.cs
using System;
public class Employee
{
public string id;
public string name;
public Employee()
{
}
public Employee(string name, string id)
{
this.name = name;
this.id = id;
}
public static int employeeCounter;
public static int AddEmployee()
{
return ++employeeCounter;
}
}
class MainClass : Employee
{
static void Main()
{
Console.Write("Enter the employee's name: ");
string name = Console.ReadLine();
Console.Write("Enter the employee's ID: ");
string id = Console.ReadLine();
// Create and configure the employee object:
Employee e = new Employee(name, id);
Console.Write("Enter the current number of employees: ");
string n = Console.ReadLine();
Employee.employeeCounter = Int32.Parse(n);
Employee.AddEmployee();
// Display the new information:
Console.WriteLine("Name: {0}", e.name);
Console.WriteLine("ID: {0}", e.id);
Console.WriteLine("New Number of Employees: {0}",
Employee.employeeCounter);
}
}