是否有任何指南可以返回类的对象?我有一个类,它有一个List和一个方法,它对列表做了一些事情并返回该列表:
public class Foo
{
private List<Bar> _myList = new List<Bar>();
public List<Bar> DoSomething()
{
// Add items to the list
return _myList;
}
}
Run Code Online (Sandbox Code Playgroud)
我不认为这是返回列表的好方法,因为现在调用方法可以修改列表,从而更新对象Foo中的列表.这可能会导致意外和不需要的行为.
你是如何处理这种情况的?您是否复制了对象(在本例中为列表)并返回该对象,或者?有没有最好的做法或技巧?
返回一个新的ReadOnlyCollection:
public ReadOnlyCollection<Bar> DoSomething()
{
// Add items to the list
return new ReadOnlyCollection<Bar>(_myList);
}
Run Code Online (Sandbox Code Playgroud)
这是列表的包装器,类型显式为只读类型.
正如@Freed所说,这不是线程安全的,因为它只是一个包装器,列表可以在Foo类中更改.
为了更好的线程安全性,请在返回之前复制一份(尽管如果这是一个要求,您应该为此开始设计类):
public ReadOnlyCollection<Bar> DoSomething()
{
// Add items to the list
return new ReadOnlyCollection<Bar>(new List<Bar>(_myList));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1723 次 |
| 最近记录: |