一週學會C#(類三)
C#才鳥(QQ:249178521)
8.常量字段<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
· 常量字段...
w 隱含爲static
w 必須在聲明時初始化
w 必須被初始化爲編譯時常量值
w 只有簡單類型,枚舉,字符串纔可以是常量
class Pair
{
public Pair(int x, int y)
{
// ???
}
...
private const int x = 0, y = 0;
}
在C#中,常量字段隱含爲static,但你不能顯式聲明一個常量字段是static:
static const int x = 0;//錯誤
常量必須被初始化,並且只能在聲明時初始化:
const int x;//錯誤
常量必須被初始化爲編譯時常量值:
const int x = Method();//錯誤
只有簡單類型,枚舉,字符串才能被聲明爲常量:
const Pair p = new Pair();//錯誤
9.靜態構造函數
· 靜態構造函數初始化類
w 可以初始化static 字段而不是const 字段
w 當類被裝載時由.net調用
w 不能被調用:沒有參數,沒有訪問修飾符
class Pair
{
public static readonly Pair Origin;
public Pair(int x, int y)
{
this.x = x;
this.y = y;
}
static Pair()
{
Origin = new Pair(0, 0);
}
private int x, y;
}
靜態構造函數只能由.net調用,而不能由程序員調用。這保證它會被調用,只被調用一次,並且在恰當的時候被調用(在任何類或類被使用前)。因爲程序員不能調用靜態構造函數,所以靜態構造函數沒有參數。出於同樣的原因,靜態構造函數不能有訪問修飾符。
靜態構造函數不能被用來初始化常量字段,即使常量字段隱式爲靜態的。因爲前面說過,常量字段必須被初始化,而且只能在它聲明的時候初始化。