C#返回私有对象

Mar*_*ijn 3 c#

是否有任何指南可以返回类的对象?我有一个类,它有一个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中的列表.这可能会导致意外和不需要的行为.

你是如何处理这种情况的?您是否复制了对象(在本例中为列表)并返回该对象,或者?有没有最好的做法或技巧?

Ode*_*ded 7

返回一个新的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)

  • 线程安全性要比这更多,无论是一直设计线程安全,还是根本不执行,开销不仅仅是为了"更加线程安全" (2认同)