簡單來說,
宣告在class中,函數外的變量可以被class中所有函數所使用。
舉個例子吧
static int a = 10;
int b=12;
public void MyTest2(int d)//非靜態方法
{
int sum = a + b + d;
Console.WriteLine(sum);
}
public static void MyTest(int a)//靜態方法
{
a = a + 1;
int x = Program.a;
Console.WriteLine(a);
Console.WriteLine(x);
}
static void Main(string[] args)
{
int c = 16;
int d = 33;
MyTest(c);
Program callNonStatic = new Program();
callNonStatic.MyTest2(d);
Console.ReadKey();
}
Main中呼叫MyTest的方法以參數c傳入被 int a接收,因為一開始就宣告了static int a,
若要使用全局變量要以Program.a的方式;而用同樣方式呼叫MyTest2會出現錯誤「需要有物件參考才能使用非靜態欄位、方法或屬性」。這是說明要使用非靜態方法要用該物件來呼叫。
如同紅色的代碼使用方式。