静态类

引用类时的 static 关键字有三个效果:

  1. 无法创建静态类的实例(这甚至会删除默认构造函数)
  2. 类中的所有属性和方法也必须是静态的。
  3. static 类是 sealed 类,意味着它不能被继承。
public static class Foo
{
    //Notice there is no constructor as this cannot be an instance
    public static int Counter { get; set; }
    public static int GetCount()
    {
        return Counter;
    }
}

public class Program 
{
    static void Main(string[] args)
    {
        Foo.Counter++;
        Console.WriteLine(Foo.GetCount()); //this will print 1
        
        //var foo1 = new Foo(); 
        //this line would break the code as the Foo class does not have a constructor
    }
}