Read-only collection with private set
有时候有这样的需求,对 List 类型变量只提供读操作,可以通过以下2种方式实现。
- 使用 ReadOnlyCollection 来实现。
private List<string> m_list; public ReadOnlyCollection<string> MyList { get { return m_list.AsReadOnly(); } private set { m_list = value; } }
- 使用IEnumerable 来实现。
private readonly List<string> m_list = new List<string>(); public IEnumerable<string> MyList { get { return m_list; } }