名单&LT; T&GT;只读了私定 [英] List<T> readonly with a private set
问题描述
我如何可以公开一个名单,其中,T&GT;
,以便它是只读的,但可以设置私人
这不工作:
公开名单&LT;字符串&GT; myList上{只读搞定;私定; }
即使你做的:
公开名单&LT;字符串&GT; myList中{获得;私定; }
您仍然可以做到这一点:
myList.Add(TEST); //这不应该被允许
我想你可以有:
公开名单&LT;字符串&GT; myList中{{返回otherList;}}
私人列表&LT;字符串&GT; otherList {获取;集;}
我觉得你混合概念。
公开名单&LT;字符串&GT; myList中{获得;私人集;}
是的已经是只读。也就是说,这个类之外,没有任何东西可以设置 myList上
到名单,其中的不同实例;串&GT;
不过,如果你想有一个只读的目录,如我不希望人们能够修改列表中的内容的,那么你需要暴露一个 ReadOnlyCollection还与LT ;字符串&GT;
。您可以通过做到这一点:
私人列表&LT;字符串&GT; actualList =新的名单,其中,串&GT;();
公共ReadOnlyCollection还&LT;字符串&GT; myList中
{
{返回actualList.AsReadOnly();}
}
请注意,在第一个code段,其他人可以操作列表,但不能改变什么列表中,您有。在第二个片段,别人会得到一个只读列表,他们不能修改。
How can I expose a List<T>
so that it is readonly but can be set privately?
This doesnt work:
public List<string> myList {readonly get; private set; }
Even if you do:
public List<string> myList {get; private set; }
You can still do this:
myList.Add("TEST"); //This should not be allowed
I guess you could have:
public List<string> myList {get{ return otherList;}}
private List<string> otherList {get;set;}
I think you are mixing concepts.
public List<string> myList {get; private set;}
is already "read-only". That is, outside this class, nothing can set myList
to a different instance of List<string>
However, if you want a readonly list as in "I don't want people to be able to modify the list contents", then you need to expose a ReadOnlyCollection<string>
. You can do this via:
private List<string> actualList = new List<string>();
public ReadOnlyCollection<string> myList
{
get{ return actualList.AsReadOnly();}
}
Note that in the first code snippet, others can manipulate the List, but can not change what list you have. In the second snippet, others will get a read-only list that they can not modify.
这篇关于名单&LT; T&GT;只读了私定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!