我的班级中有一个List<string> myList
我想对班级用户只读。
List<strign> myList {get;}
private void SetListValue()
{
myList = new List<string>();
myList.Add("ss");
}
像这样,我认为我可以myList
在我的私人成员中设置我的班级内的值,并使其对班级用户只读。但我意识到,以这种方式声明它我无法设置任何值。
尝试:
public List<string> myList {get; private set;}
这将让您将其设置在您的班级内部,而不是外部。请注意,这不会阻止外部客户端更新您的列表,只会停止对它的引用。
List、Collection 等的私有 setter 意味着整个列表不能被消费者替换,但它对保护列表的公共成员没有任何作用。
例如:
public class MyClass
{
public IList<string> MyList {get; private set;}
public MyClass()
{
MyList = new List<string>(){"One","Two", "Three"};
}
}
public class Consumer
{
public void DoSomething()
{
MyClass myClass = new MyClass();
myClass.MyList = new List<string>(); // This would not be allowed,
// due to the private setter
myClass.MyList.Add("new string"); // This would be allowed, because it's
// calling a method on the existing
// list--not replacing the list itself
}
}
为了防止消费者更改列表的成员,您可以将其公开为只读接口,例如IEnumerable<string>
, ,或通过在声明类中ReadOnlyCollection<string>
调用。List.AsReadOnly()
public class MyClass
{
public IList<string> MyList {get; private set;}
public MyClass()
{
MyList = new List<string>(){"One","Two", "Three"}.AsReadOnly();
}
}
public class Consumer
{
public void DoSomething()
{
MyClass myClass = new MyClass();
myClass.MyList = new List<string>(); // This would not be allowed,
// due to the private setter
myClass.MyList.Add("new string"); // This would not be allowed, the
// ReadOnlyCollection<string> would throw
// a NotSupportedException
}
}
你想要一个带有私有 setter 的公共属性。如下。
public List<string> myList { get; private set; }