static

使用 static 修饰符声明属于类型本身而不是属于特定对象的静态成员。static 修饰符可用于字段、方法、属性、运算符、事件和构造函数,但不能用于索引器、析构函数或类型。

备注
  • 常数或者类型声明隐式地是静态成员。
  • 不能通过实例引用静态成员。然而,可以通过类型名称引用它。例如,请考虑以下类:
    public class MyBaseC 
    {
       public struct MyStruct {
          public static int x = 100;
       }
    }

    若要引用静态成员 x,请使用完全限定名(除非可从相同范围访问):

    MyBaseC.MyStruct.x
  • 尽管类的实例包含该类所有实例字段的单独副本,但每个静态字段只有一个副本。
  • 不可以使用 this 引用静态方法或属性访问器。
    注意   static 关键字在使用上比在 C++ 中有更多限制。若要与 C++ 关键字进行比较,请参见 C++ Language Reference 中的 static 。

为了说明实例成员,请看一个表示公司雇员的类。假设该类包含一种对雇员计数的方法和一个存储雇员数的字段。该方法和字段都不属于任何实例雇员,而是属于公司类。因此,应该将它们声明为此类的静态成员。

有关构造函数的更多信息,请参见 10.10 实例构造函数 。

示例

该示例读取新雇员的名称和 ID,逐个增加雇员计数器并显示新雇员的有关信息以及新的雇员数。为简单起见,该程序从键盘读取当前的雇员数。在实际的应用中,应从文件读取此信息。

// cs_static_keyword.cs
// Static members
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 
{
   public 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 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);
   }
}
输入
Tara Strahan
AF643G
15
示例输出
Enter the employee's name: Tara Strahan
Enter the employee's ID: AF643G
Enter the current number of employees: 15
Name: Tara Strahan
ID:   AF643G
New Number of Employees: 16
请参见

C# 关键字 | 修饰符

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值