列表<T>只读与私有集 [英] List&lt;T&gt; readonly with a private set

查看:22
本文介绍了列表<T>只读与私有集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何公开 List 以便它是只读的,但可以私下设置?

How can I expose a List<T> so that it is readonly, but can be set privately?

这不起作用:

public List<string> myList {readonly get; private set; }

即使你这样做:

public List<string> myList {get; private set; }

你仍然可以这样做:

myList.Add("TEST"); //This should not be allowed

我猜你可能有:

public List<string> myList {get{ return otherList;}}
private List<string> otherList {get;set;}

推荐答案

我认为你在混淆概念.

public List<string> myList {get; private set;}

已经只读"了.也就是说,在这个类之外,没有什么可以将 myList 设置为 List

is already "read-only". That is, outside this class, nothing can set myList to a different instance of List<string>

但是,如果您想要一个只读列表,如我不希望人们能够修改列表内容",那么您需要公开一个 ReadOnlyCollection;.您可以通过以下方式执行此操作:

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.

这篇关于列表<T>只读与私有集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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