T&GT;我应该如何使用只读名单,LT打交道时使用性能;会员 [英] How should I use properties when dealing with read-only List<T> members
问题描述
当我想打一个值类型只读超出了我的班我这样做:
公共类myClassInt
{
私人诠释m_i;
公众诠释我{
{返回m_i; }
} 公共myClassInt(int i)以
{
m_i = I;
}
}
我能做些什么使一个列表&LT; T&GT;
键入只读(所以他们不能添加/删除其元素/)我的课之外吗?现在,我只是把它声明市民:
公共类myClassList
{
公开名单&LT; INT&GT;立;
公共myClassList()
{
LI =新的List&LT; INT&GT;();
li.Add(1);
li.Add(2);
li.Add(3);
}
}
您可以将其暴露 AsReadOnly 一>。也就是说,返回一个只读的IList&LT; T&GT;
包装。例如...
公共ReadOnlyCollection还&LT; INT&GT;名单
{
{返回_lst.AsReadOnly(); }
}
就返回一个的IEnumerable&LT; T&GT;
是不够的。例如...
无效的主要()
{
VAR EL =新ExposeList();
VAR LST = el.ListEnumerator;
VAR哎呀=(IList的&LT; INT&GT;)LST;
oops.Add(4); //变异名单 VAR ROL = el.ReadOnly;
VAR oops2 =(IList的&LT; INT&GT;)ROL; oops2.Add(5); //产生异常
}类ExposeList
{
私人列表&LT; INT&GT; _lst =新列表与所述; INT&GT;(){1,2,3}; 公共IEnumerable的&LT; INT&GT; ListEnumerator
{
{返回_lst; }
} 公共ReadOnlyCollection还&LT; INT&GT;只读
{
{返回_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屋!