List<string> myList我的班级里有一个我想要只为班级用户阅读.
List<strign> myList {get;}
private void SetListValue()
{
myList = new List<string>();
myList.Add("ss");
}
Run Code Online (Sandbox Code Playgroud)
像这样我认为我可以myList在我的私有成员中设置我的类中的值,并为类用户提供readonly.但我意识到以这种方式宣布它我无法设置任何价值.
Adr*_*agg 11
尝试:
public List<string> myList {get; private set;}
Run Code Online (Sandbox Code Playgroud)
这可以让你在课堂上设置,但不在外面.请注意,这不会阻止外部客户端更新列表,只会停止对其的引用.
列表,集合等的私有设置器意味着整个列表不能被消费者替换,但它不会保护列表的公共成员.
例如:
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
}
}
Run Code Online (Sandbox Code Playgroud)
为了防止消费者改变列表的成员,你可以公开为只读接口,如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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
325 次 |
| 最近记录: |