How should I use properties when dealing with read-only List members

后端 未结 7 1457
栀梦
栀梦 2020-12-01 08:26

When I want to make a value type read-only outside of my class I do this:

public class myClassInt
{
    private int m_i;
    public int i {
        get { ret         


        
7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-01 09:09

    JP's answer regarding returning IEnumerable is correct (you can down-cast to a list), but here is a technique that prevents the down-cast.

    class ExposeList
    {
      private List _lst = new List() { 1, 2, 3 };
    
      public IEnumerable ListEnumerator
      {
         get { return _lst.Select(x => x); }  // Identity transformation.
      }
    
      public ReadOnlyCollection ReadOnly
      {
         get { return _lst.AsReadOnly(); }
      }
    }
    

    The identity transformation during enumeration effectively creates a compiler-generated iterator - a new type which is not related to _lst in any way.

提交回复
热议问题