Read-only collection with private set

有时候有这样的需求,对 List 类型变量只提供读操作,可以通过以下2种方式实现。

  1. 使用 ReadOnlyCollection 来实现。
    private List<string> m_list;
      
    public ReadOnlyCollection<string> MyList
    {
        get { return m_list.AsReadOnly(); }
        private set { m_list = value; }   
    }
  2. 使用IEnumerable 来实现。
    private readonly List<string> m_list = new List<string>();
    
    public IEnumerable<string> MyList
    {
       get { return m_list; }
    }
ReadOnlyCollection on MSDN
posted @ 2011-12-06 16:41  Junde  阅读(280)  评论(0编辑  收藏  举报