Jon*_*Jon 50 .net c# generics c#-3.0
我怎样才能公开一个List<T>
只读它,但可以私下设置?
这不起作用:
public List<string> myList {readonly get; private set; }
Run Code Online (Sandbox Code Playgroud)
即使你这样做:
public List<string> myList {get; private set; }
Run Code Online (Sandbox Code Playgroud)
你仍然可以这样做:
myList.Add("TEST"); //This should not be allowed
Run Code Online (Sandbox Code Playgroud)
我想你可以:
public List<string> myList {get{ return otherList;}}
private List<string> otherList {get;set;}
Run Code Online (Sandbox Code Playgroud)
Phi*_*eck 96
我认为你正在混合概念.
public List<string> myList {get; private set;}
Run Code Online (Sandbox Code Playgroud)
已经是 "只读"了.也就是说,在这个类之外,没有任何东西可以设置myList
为不同的实例List<string>
但是,如果您想要一个只读列表,如"我不希望人们能够修改列表内容 ",那么您需要公开一个ReadOnlyCollection<string>
.你可以这样做:
private List<string> actualList = new List<string>();
public ReadOnlyCollection<string> myList
{
get{ return actualList.AsReadOnly();}
}
Run Code Online (Sandbox Code Playgroud)
请注意,在第一个代码段中,其他人可以操作List,但无法更改您拥有的列表.在第二个片段中,其他人将获得一个他们无法修改的只读列表.
Dar*_*rov 11
如果您想要只读集合使用ReadOnlyCollection<T>
,而不是List<T>
:
public ReadOnlyCollection<string> MyList { get; private set; }
Run Code Online (Sandbox Code Playgroud)
Ser*_*kiy 11
我更喜欢使用IEnumerable
private readonly List<string> _list = new List<string>();
public IEnumerable<string> Values // Adding is not allowed - only iteration
{
get { return _list; }
}
Run Code Online (Sandbox Code Playgroud)
Sea*_*ean 10
返回一个ReadOnlyCollection,它实现了IList <>
private List<string> myList;
public IList<string> MyList
{
get{return myList.AsReadOnly();}
}
Run Code Online (Sandbox Code Playgroud)