处理只读 List<T> 时应该如何使用属性?成员 [英] How should I use properties when dealing with read-only List<T> members
本文介绍了处理只读 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;
}
}
我该怎么做才能在我的班级之外使 List
类型成为只读(这样他们就不能在其中添加/删除元素)?现在我只是宣布它是公开的:
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);
}
}
推荐答案
你可以公开它 作为只读.也就是说,返回一个只读的 IList
包装器.例如...
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
是不够的.例如...
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.
这篇关于处理只读 List<T> 时应该如何使用属性?成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文