gpt4 book ai didi

c# - C# 中的只读列表

转载 作者:可可西里 更新时间:2023-11-01 07:48:49 25 4
gpt4 key购买 nike

我有一些带有 List-property 的类:

class Foo {
private List<int> myList;
}

我只想提供对该字段的访问权限以供读取。

即我想要属性可以访问 Enumerable、Count 等,但不能访问 Clear、Add、Remove 等。我该怎么做?

最佳答案

您可以公开一个 List<T>作为 ReadOnlyCollection<T>通过使用 AsReadOnly()方法

C# 6.0 及更高版本(使用 Expression Bodied Properties )

class Foo { 

private List<int> myList;

public ReadOnlyCollection<int> ReadOnlyList => myList.AsReadOnly();

}

C# 5.0 及更早版本

class Foo {

private List<int> myList;

public ReadOnlyCollection<int> ReadOnlyList {
get {
return myList.AsReadOnly();
}
}
}

关于c# - C# 中的只读列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4680035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com