在处理只读列表时应该如何使用属性List< T>成员 [英] How should I use properties when dealing with read-only List<T> members

查看:139
本文介绍了在处理只读列表时应该如何使用属性List< T>成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想使值类型只读在我的类之外时,我这样做:

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 { return m_i; }
    }

    public myClassInt(int i)
    {
        m_i = i;
    }
}

c> List< T> 在我的类外部类型readonly(因此他们不能添加/删除元素)现在我只是将它公开:

What can I do to make a List<T> type readonly (so they can't add/remove elements to/from it) outside of my class? Now I just declare it public:

public class myClassList
{
    public List<int> li;
    public  myClassList()
    {
        li = new List<int>();
        li.Add(1);
        li.Add(2);
        li.Add(3);
    }
}


推荐答案

可以公开它 AsReadOnly 。也就是说,返回只读 IList< T> 包装器。例如...

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

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

只需返回 IEnumerable< T& code>是不够的。例如...

Just returning an IEnumerable<T> is not sufficient. For example ...

void Main()
{
    var el = new ExposeList();
    var lst = el.ListEnumerator;
    var oops = (IList<int>)lst;
    oops.Add( 4 );  // mutates list

    var rol = el.ReadOnly;
    var oops2 = (IList<int>)rol;

    oops2.Add( 5 );  // raises exception
}

class ExposeList
{
  private List<int> _lst = new List<int>() { 1, 2, 3 };

  public IEnumerable<int> ListEnumerator
  {
     get { return _lst; }
  }

  public ReadOnlyCollection<int> ReadOnly
  {
     get { return _lst.AsReadOnly(); }
  }
}

Steve的回答还有一个聪明的方法来避免强制转换。

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

这篇关于在处理只读列表时应该如何使用属性List&lt; T&gt;成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆