类的静态(Static)成员——字段
定义一个雇员类:
namespace StaticFieldTest1 { class Employee { public int Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Salary { get; set; } // public static int NextId; public Employee(string firstName, string lastName) { FirstName = firstName; LastName = lastName; Id = NextId; NextId++; } } }
使用雇员类:
using System; namespace StaticFieldTest1 { class Program { static void Main(string[] args) { Employee.NextId = 100000; Employee employee1 = new Employee("Inigo", "Montoya"); Employee employee2 = new Employee("Princess", "Buttercup"); Console.WriteLine("{0} {1} ({2})", employee1.FirstName, employee1.LastName, employee1.Id); Console.WriteLine("{1} {1} ({2})", employee2.FirstName, employee2.LastName, employee2.Id); Console.WriteLine("NextId = {0}", Employee.NextId); Console.ReadKey(); } } }
输出:
Inigo Montoya (100000)
Buttercup Buttercup (100001)
NextId = 100002