只读在C#列表列表

2023-09-03 05:01:15 作者:霸气为了你~

我有一些类列表 -property:

I have some class with List-property:

class Foo {
  private List<int> myList;
}

我想只为读提供访问该字段。

I want provide access to this field only for read.

即。我希望财产获得枚举的,计数等,也得不到清除,添加,删除等,我该怎么办呢?

I.e. I want property with access to Enumerable, Count, etc. and without access to Clear, Add, Remove, etc. How I can do it?

推荐答案

如果你想要一个不变的列表,你可以使用ReadOnlyCollection<T>.

If you want an immutable list you could use ReadOnlyCollection<T>.

class Foo {
    private ReadOnlyCollection<int> myList;
}
 
精彩推荐
图片推荐