靜態類
引用類時的 static
關鍵字有三個效果:
- 你無法建立靜態類的例項(這甚至會刪除預設建構函式)
- 類中的所有屬性和方法也必須是靜態的。
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
}
}