C#泛型秘訣(6)

來源:互聯網
上載者:User

4.9 使用泛型建立唯讀集合

問題

您希望類中的一個集合裡的資訊可以被外界訪問,但不希望使用者改變這個集合。

解決方案

使用ReadOnlyCollection<T>封裝就很容易實現唯讀集合類。例子如,Lottery類包含了中獎號碼,它可以被訪問,但不允許被改變:

public class Lottery
  {
    // 建立一個列表.
    List<int> _numbers = null;
    public Lottery()
    {
      // 初始化內部列表
      _numbers = new List<int>(5);
      // 添加值
      _numbers.Add(17);
      _numbers.Add(21);
      _numbers.Add(32);
      _numbers.Add(44);
      _numbers.Add(58);
    }
    public ReadOnlyCollection<int> Results
    {
      // 返回一份封裝後的結果
      get { return new ReadOnlyCollection<int>(_numbers); }
    }
}

Lottery有一個內部的List<int>,它包含了在構造方法中被填的中獎號碼。有趣的部分是它有一個公有屬性叫Results,通過返回的ReadOnlyCollection<int>類型可以看到其中的中獎號碼,從而使使用者通過返回的執行個體來使用它。

如果使用者試圖設定集合中的一個值,將引發一個編譯錯誤:

Lottery tryYourLuck = new Lottery();
  // 列印結果.
  for (int i = 0; i < tryYourLuck.Results.Count; i++)
  {
    Console.WriteLine("Lottery Number " + i + " is " + tryYourLuck.Results[i]);
  }
  // 改變中獎號碼!
  tryYourLuck.Results[0]=29;
  //最後一行引發錯誤:// Error 26 // Property or indexer
  // 'System.Collections.ObjectModel.ReadOnlyCollection<int>.this[int]'
  // cannot be assigned to -- it is read only

討論

ReadOnlyCollection的主要優勢是使用上的靈活性,可以在任何支援IList或IList<T>的集合中把它做為介面使用。ReadOnlyCollection還可以象這樣封裝一般數組:

int [] items = new int[3];
  items[0]=0;
  items[1]=1;
  items[2]=2;
new ReadOnlyCollection<int>(items);

這為類的唯讀屬性的標準化提供了一種方法,並使得類庫使用人員習慣於這種簡單的唯讀屬性傳回型別。

閱讀參考

查看MSDN文檔中的“IList”和“Generic IList”主題。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.