gpt4 book ai didi

c# - 为什么我收到错误 : "cannot implicitly convert type System.Collections.Generic.List"

转载 作者:太空狗 更新时间:2023-10-29 21:18:08 30 4
gpt4 key购买 nike

我有以下密封类。我试图将列表作为 ReadOnlyCollection 返回。尝试了几件事,但我不明白这一点。那么如何将列表返回或转换为只读集合?

    public sealed class UserValues
{
private readonly List<UserValue> _Values = new List<UserValue>();

public ReadOnlyCollection<UserValues> Values
{
get
{
return _Values;
}
}
}

最佳答案

您收到编译时错误是因为 List<UserValue> 不是 ReadOnlyCollection<UserValue> ,也不能隐式转换为那个。 (顺便说一句,我假设你的意思是 ReadOnlyCollection<UserValue> 而不是 ReadOnlyCollection<UserValues>?)

使用 List<T>.AsReadOnly 可能是最简单的- 但您最好只创建一次:

public sealed class UserValues
{
private readonly List<UserValue> values = new List<UserValue>();
private readonly ReadOnlyCollection<UserValue> valuesView;

public UserValues()
{
valuesView = values.AsReadOnly();
}

public ReadOnlyCollection<UserValues> Values { get { return valuesView; } }
}

ReadOnlyCollection<T>实际上只是一个 View - 因此通过 View 可以看到对基础集合的更改。

关于c# - 为什么我收到错误 : "cannot implicitly convert type System.Collections.Generic.List",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16388740/

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