具有私有集的只读 List

2024-01-06

我怎样才能暴露List<T>这样它是只读的,但可以私下设置?

这不起作用:

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;}

is已经是“只读”。也就是说,在这个类之外,什么都不能设置myList到另一个实例List<string>

但是,如果您想要一个只读列表,如“我不希望人们能够修改列表”contents”,那么你需要暴露一个ReadOnlyCollection<string>。您可以通过以下方式执行此操作:

private List<string> actualList = new List<string>();
public ReadOnlyCollection<string> myList
{
  get{ return actualList.AsReadOnly();}
}

请注意,在第一个代码片段中,其他人可以操作列表,但不能更改您拥有的列表。在第二个片段中,其他人将获得他们无法修改的只读列表。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

具有私有集的只读 List 的相关文章

随机推荐