【问题标题】:Cannot implicitly convert type void to IList<int>无法将类型 void 隐式转换为 IList<int>
【发布时间】:2009-10-07 00:33:52
【问题描述】:
 string categoryIDList = Convert.ToString(reader["categoryIDList"]);

    if (!String.IsNullOrEmpty(categoryIDList))
    {
        c.CategoryIDList  =
            new List<int>().AddRange(
                categoryIDList 
                    .Split(',')
                    .Select(s => Convert.ToInt32(s)));

    }

该类有一个属性 IList CategoryIDList 我试图分配给上面。

错误:

错误 1 ​​无法将类型“void”隐式转换为“System.Collections.Generic.IList”

不确定是什么问题?

【问题讨论】:

    标签: c# oop


    【解决方案1】:

    您的问题是 AddRange method of the generic List class 被声明为返回 void。

    更新:已编辑以修复 List&lt;int&gt; 与 IList&lt;int&gt; 的问题。

    您需要将其更改为:

    List<int> foo = new List<int>();
    foo.AddRange(
        categoryIDList 
        .Split(',')
        .Select(s => Convert.ToInt32(s)));
    c.CategoryIDList = foo;
    

    【讨论】:

    • Arghh,IList 不支持 AddRange 吗? c.CategoryIDList 是 IList 类型
    • 是的,这不会按原样编译。
    • @homestead & Reed Copsey:是的,很抱歉。简单的解决方案就是使用List&lt;int&gt; 类型的临时变量。请参阅我的编辑以获取一种可能的解决方案。
    【解决方案2】:

    为什么不用选择查询的结果来初始化列表,而不是使用 AddRange,因为它将 IEnumerable 作为重载:

    c.CategoryIDList = new List<int>(categoryIDList.Split(',')
     .Select(s => Convert.ToInt32(s)));
    

    【讨论】:

      【解决方案3】:

      AddRange 不返回列表 - 它返回 void。您可以通过 List&lt;T&gt; that takes an enumerable 的构造函数来做到这一点:

      string categoryIDList = Convert.ToString(reader["categoryIDList"]);
      
      if (!String.IsNullOrEmpty(categoryIDList))
      {
          c.CategoryIDList  =
              new List<int>(
                  categoryIDList.Split(',').Select(s => Convert.ToInt32(s))
              );
      }
      

      【讨论】:

        【解决方案4】:

        为了更好地了解正在发生的事情,我创建了下面的示例。 解决方案应基于 1. list.AddRange,2. 然后将列表重新分配给其他内容:

        List<int> list1 = new List<int>{1,4, 8};
        List<int> list2 = new List<int> { 9, 3, 1 };
        //this will cause compiler error "AddRange cannot convert source type void to target type List<>"
        //List<int> list3 = list1.AddRange(list2); 
        //do something like this:
        List<int> list3 = new List<int>();
        list3.AddRange(list1);
        list3.AddRange(list2);
        

        【讨论】:

          【解决方案5】:

          您将 AddRange 的结果分配给 c.CategoryIDList,而不是新列表本身。

          【讨论】:

            猜你喜欢
            • 2016-02-17
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-02-22
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多