【问题标题】:Cannot implicitly convert type 'string' to 'System.Collections.Generic.List<string>' c# class getter无法将类型'string'隐式转换为'System.Collections.Generic.List<string>' c# class getter
【发布时间】:2019-12-18 18:07:25
【问题描述】:
class Fridge {
    public List<string> Food
    {
        get {
            string aliments = "";
            foreach (string aliment in Food)
            {
                aliments += $"{aliment} ";
            }
            return aliments;
        }
    }

我正在尝试获取冰箱内所有食物的字符串,当我尝试运行代码时出现以下错误无法将类型“字符串”隐式转换为“System.Collections.Generic.List”

【问题讨论】:

    标签: c# class get


    【解决方案1】:

    将getter的返回类型改为string而不是List&lt;string&gt;。

    public string Food  // <-- return type should be string, not List<string>
    {
        get {
            string aliments = "";
            foreach (string aliment in Food)
            {
                aliments += $"{aliment} ";
            }
            return aliments;
        }
    }
    

    【讨论】:

      【解决方案2】:

      你说过你的函数会返回一个字符串集合——准确地说是List&lt;string&gt;。

      然而你的返回值只是一个单个字符串。作为大多数 .NET 语言的 C# 对隐式转换非常谨慎。这显然超出了它的作用。

      您要么想要创建和填充集合。或者使用连接字符串。请决定。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-04
        相关资源
        最近更新 更多