防止其他班级更改班级中的列表 [英] Prevent other classes from altering a list in a class
问题描述
如果我有一个包含例如List< string>并且我希望其他类能够看到列表,但不能看到列表,可以声明
If I have a class that contains, for example, a List<string> and I want other classes to be able to see the list but not set it, I can declare
public class SomeClass()
{
public List<string> SomeList { get; }
}
这将允许另一个类访问SomeList而不进行设置。
This will allow another class to access SomeList and not set it.
但是,尽管调用类无法设置列表,但是它可以添加或删除元素。我该如何预防?我想我可以使用一个字段并返回List的副本而不是使用属性,但这感觉并不正确。
However, although the calling class can't set the list, it can add or remove elements. How do I prevent that? I guess I could use a field and return a copy of the List instead of using a property, but that just doesn't feel right.
(这应该非常简单但是我一定会缺少某些东西。...
(This should be very simple but I must be missing something....)
推荐答案
您将无法使用自动属性。
You won't be able to use an autoproperty.
public class SomeClass()
{
private List<string> someList;
public IList<string> SomeList {
get { return someList.AsReadOnly(); }
}
}
这篇关于防止其他班级更改班级中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!