名单< T>只读了私定 [英] List<T> readonly with a private set

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

问题描述

我如何可以公开一个名单,其中,T> ,以便它是只读的,但可以设置私人

这不工作:

 公开名单<字符串> myList上{只读搞定;私定; }
 

即使你做的:

 公开名单<字符串> myList中{获得;私定; }
 

您仍然可以做到这一点:

  myList.Add(TEST); //这不应该被允许
 

我想你可以有:

 公开名单<字符串> myList中{{返回otherList;}}
私人列表<字符串> otherList {获取;集;}
 

解决方案

我觉得你混合概念。

 公开名单<字符串> myList中{获得;私人集;}
 

的已经是只读。也就是说,这个类之外,没有任何东西可以设置 myList上名单,其中的不同实例;串>

不过,如果你想有一个只读的目录,如我不希望人们能够修改列表中的内容的,那么你需要暴露一个 ReadOnlyCollection还与LT ;字符串> 。您可以通过做到这一点:

 私人列表<字符串> actualList =新的名单,其中,串>();
公共ReadOnlyCollection还<字符串> 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屋!

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