为什么我收到错误:"无法隐式转换类型System.Collections.Generic.List"

Deb*_*bie 6 c# readonly-collection

我有以下密封课.我正试图将列表作为一个返回ReadOnlyCollection.尝试了几件事,但我没有掌握这一点.那么如何将列表返回或转换为只读集合?

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

        public ReadOnlyCollection<UserValues> Values
        {
            get
            {
                return _Values;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Gje*_*ema 4

尝试:

return new ReadOnlyCollection<UserValue>(_Values);
Run Code Online (Sandbox Code Playgroud)

编辑:

鉴于您对乔恩所说的话,您的代码没有意义。您get正在引用 的类型List<UserValue>,但您希望将其转换为 的类型ReadOnlyCollection<UserValues>,但这是无法完成的 - 这是 2 个不同类型的 2 个集合。

我们需要更多信息来帮助您回答这个问题。您希望您的UserValues类返回UserValues类型的集合,还是类型的集合UserValue?您的代码暗示了这一点UserValue,但您对评论的关注状态UserValues。你确定你的主管没有打错字吗?

如果没有,您将需要一些内部集合,如下所示:

private readonly List<UserValues> _MoreValues = new List<UserValues>();
Run Code Online (Sandbox Code Playgroud)

然后以我(或其他已回答的人 - 给出的所有答案对于将 List 转换为 ReadOnlyCollection 有效)显示的语法返回该内容。

请注意,我的代码以 .Net 3.5 为目标进行编译,假设类型是兼容的(意味着ReadOnlyCollection<UserValue>wraps List<UserValue>,或两者都是UserValues)。