List readonly with a private set

后端 未结 15 1978
北海茫月
北海茫月 2020-11-30 01:57

How can I expose a List so that it is readonly, but can be set privately?

This doesn\'t work:

public List myList          


        
15条回答
  •  遥遥无期
    2020-11-30 02:07

    In the .NET 4.5 framework you can expose only the IReadOnlyList interface. Something like:

    private List _mylist;
    public IReadOnlyList myList { get {return _myList;} }
    

    or if you want to prevent unwanted casting to IList

    private List _mylist;
    public IReadOnlyList myList { get {return new List(_myList);} }
    

提交回复
热议问题