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

后端 未结 7 1491
栀梦
栀梦 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:21

    You can expose it AsReadOnly. That is, return a read-only IList wrapper. For example ...

    public ReadOnlyCollection List
    {
        get { return _lst.AsReadOnly(); }
    }
    

    Just returning an IEnumerable is not sufficient. For example ...

    void Main()
    {
        var el = new ExposeList();
        var lst = el.ListEnumerator;
        var oops = (IList)lst;
        oops.Add( 4 );  // mutates list
    
        var rol = el.ReadOnly;
        var oops2 = (IList)rol;
    
        oops2.Add( 5 );  // raises exception
    }
    
    class ExposeList
    {
      private List _lst = new List() { 1, 2, 3 };
    
      public IEnumerable ListEnumerator
      {
         get { return _lst; }
      }
    
      public ReadOnlyCollection ReadOnly
      {
         get { return _lst.AsReadOnly(); }
      }
    }
    

    Steve's answer also has a clever way to avoid the cast.

提交回复
热议问题