gpt4 book ai didi

c# - 如何返回集合的只读副本

转载 作者:可可西里 更新时间:2023-11-01 08:04:20 25 4
gpt4 key购买 nike

我有一个包含集合的类。我想提供一个返回集合内容的方法或属性。如果调用类可以修改单个对象是可以的,但我不希望它们在实际集合中添加或删除对象。我一直在将所有对象复制到一个新列表,但现在我想我可以将列表作为 IEnumerable<> 返回。

在下面的简化示例中,GetListC 是返回集合的只读版本的最佳方式吗?

public class MyClass
{
private List<string> mylist;

public MyClass()
{
mylist = new List<string>();
}

public void Add(string toAdd)
{
mylist.Add(toAdd);
}

//Returns the list directly
public List<String> GetListA
{
get
{
return mylist;
}
}

//returns a copy of the list
public List<String> GetListB
{
get
{
List<string> returnList = new List<string>();

foreach (string st in this.mylist)
{
returnList.Add(st);
}
return returnList;
}
}

//Returns the list as IEnumerable
public IEnumerable<string> GetListC
{
get
{
return this.mylist.AsEnumerable<String>();
}

}

}

最佳答案

您可以使用 List(T).AsReadOnly() :

return this.mylist.AsReadOnly()

这将返回 ReadOnlyCollection .

关于c# - 如何返回集合的只读副本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/853911/

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