在C#中,一个方法可以返回List,这样客户端只能读取它,而不能写入它吗?

时间:2009-10-21 04:36:13

标签: c# const encapsulation immutability readonly

假设我有一个C#类:

class Foo
{
    private List<Bar> _barList;
    List<Bar> GetBarList() { return _barList; }
...
}

客户可以拨打电话:

var barList = foo.GetBarList();
barList.Add( ... );

有没有办法让Add方法失败,因为只返回了_barList的只读版本?

2 个答案:

答案 0 :(得分:16)

是的,在GetBarList()返回_barList.AsReadOnly()

修改
正如迈克尔在下面指出的那样,您的方法必须返回IList<Bar>

答案 1 :(得分:4)

您可以尝试使用ReadOnlyCollection。或者从您的方法返回IEnumerable,客户端将没有方法来修改它。