多個建構子需初始化相同欄位時,可用 this(...) 呼叫另一建構子避免重複。
public class Test {
private string domain, url;
public Test(string dom, string url) {
this.domain = dom; this.url = url;
}
public Test(string dom) : this(dom, "www.gosoa.com.cn") { }
static void Main() {
Test t = new Test("gosoa");
Console.WriteLine(t.url); // www.gosoa.com.cn
}
}
: this(...) 為建構子初始化器,於建構子本體之前執行。
const 彈性大:const 宣告時必須初始化;readonly 可在建構子中運算後指派。