T>我应该如何使用只读名单,LT打交道时使用性能;会员 [英] How should I use properties when dealing with read-only List<T> members

查看:94
本文介绍了T>我应该如何使用只读名单,LT打交道时使用性能;会员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想打一个值类型只读超出了我的班我这样做:

 公共类myClassInt
{
    私人诠释m_i;
    公众诠释我{
    {返回m_i; }
    }    公共myClassInt(int i)以
    {
    m_i = I;
    }
}

我能做些什么使一个列表< T> 键入只读(所以他们不能添加/删除其元素/)我的课之外吗?现在,我只是把它声明市民:

 公共类myClassList
{
    公开名单< INT>立;
    公共myClassList()
    {
    LI =新的List< INT>();
    li.Add(1);
    li.Add(2);
    li.Add(3);
    }
}


解决方案

您可以将其暴露 AsReadOnly 。也就是说,返回一个只读的IList< T> 包装。例如...

 公共ReadOnlyCollection还< INT>名单
{
    {返回_lst.AsReadOnly(); }
}

就返回一个的IEnumerable< T> 是不够的。例如...

 无效的主要()
{
    VAR EL =新ExposeList();
    VAR LST = el.ListEnumerator;
    VAR哎呀=(IList的< INT>)LST;
    oops.Add(4); //变异名单    VAR ROL = el.ReadOnly;
    VAR oops2 =(IList的< INT>)ROL;    oops2.Add(5); //产生异常
}类ExposeList
{
  私人列表< INT> _lst =新列表与所述; INT>(){1,2,3};  公共IEnumerable的< INT> ListEnumerator
  {
     {返回_lst; }
  }  公共ReadOnlyCollection还< INT>只读
  {
     {返回_lst.AsReadOnly(); }
  }
}

<一个href=\"http://stackoverflow.com/questions/1230293/c-how-should-i-use-properties-when-dealing-with-listt-members/1230412#1230412\">Steve's回答也有一个聪明的方法来避免偏色。

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;
    }
}

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);
    }
}

解决方案

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

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

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's answer also has a clever way to avoid the cast.

这篇关于T&GT;我应该如何使用只读名单,LT打交道时使用性能;会员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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