首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 進階(三):建構子初始化器與唯讀欄位

     編輯:關於C語言

建構子初始化器

多個建構子需初始化相同欄位時,可用 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(...) 為建構子初始化器,於建構子本體之前執行。

2. 唯讀欄位

  • 比 const 彈性大:const 宣告時必須初始化;readonly 可在建構子中運算後指派。
  • 只能在建構子中指派,其他位置不可修改。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved