开发者

In C#, can a method return List such that clients can only read it, but not write to it?

开发者 https://www.devze.com 2022-12-09 04:37 出处:网络
Let\'s say I have a C# class: class Foo { private List<Bar> _barList; List<Bar> GetBarList() { return _barList开发者_Go百科; }

Let's say I have a C# class:

class Foo
{
    private List<Bar> _barList;
    List<Bar> GetBarList() { return _barList开发者_Go百科; }
...
}

A client can call it:

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

Is there a way to make the Add method fail because only a read-only version of _barList is returned?


Yes, in GetBarList() return _barList.AsReadOnly().

Edit:
As Michael pointed out below, your method would have to return an IList<Bar>.


You may try to use ReadOnlyCollection. Or return just IEnumerable from your method, clients will not have methods to modify it.

0

精彩评论

暂无评论...
验证码 换一张
取 消