Gab*_*lli 2 c# field private public readonly
我有一个名为的类GestorePersonale,它包含另一个类的实例列表:
public List<Dipendente> Dipendenti
{
get;
private set;
}
我想保持这个列表只能从类暴露的方法中修改,而不是直接修改.我注意到,使用上面的代码,人们可以做到
var gp = new GestorePersonale(); gp.Dipendenti.Add( new Dipendente( ... ) );并能够对自己进行任何其他类型的行动
List<Dipendente>.
我考虑过将第一个代码段转换为
private List dipendenti;
但我可以找到一些缺点:
什么是解决这种情况的最佳方法?
您可以将列表包装在ReadOnlyCollection <T>中并公开:
private List<Dipendente> dipendenti;
private ReadOnlyCollection<Dipendente> readOnlyDipendenti;
public GestorePersonale()
{
dipendenti = new List<Dipendente>();
readOnlyDipendenti = new ReadOnlyCollection<Dipendente>(dipendenti);
}
public ReadOnlyCollection<Dipendente> Dipendenti
{
get { return readOnlyDipendenti; }
}
Run Code Online (Sandbox Code Playgroud)
在内部,您可以访问dipendenti并添加/删除项目.外部实体只能访问包装列表的ReadOnlyCollection <T>,因此它们只能读取,但不能添加/删除项目.
| 归档时间: |
|
| 查看次数: |
244 次 |
| 最近记录: |