Prevent other classes from altering a list in a class

后端 未结 4 1479
深忆病人
深忆病人 2020-12-06 05:53

If I have a class that contains, for example, a List and I want other classes to be able to see the list but not set it, I can declare



        
4条回答
  •  猫巷女王i
    2020-12-06 06:57

    You'll want to return the list as a ReadOnly list. You can do this with the following code:

    using System.Collections.ObjectModel;
    
    public ReadOnlyCollection GetList() {
        return SomeList.AsReadOnly();
    }
    

提交回复
热议问题