简体   繁体   English

无法将类型void隐式转换为IList <int>

[英]Cannot implicitly convert type void to IList<int>

 string categoryIDList = Convert.ToString(reader["categoryIDList"]);

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

    }

The class has a property IList CategoryIDList that I am trying to assign to above. 该类具有一个IList CategoryIDList属性,我正在尝试将其分配给该属性。

Error: 错误:

Error 1 Cannot implicitly convert type 'void' to 'System.Collections.Generic.IList' 错误1无法将类型'void'隐式转换为'System.Collections.Generic.IList'

Not sure what the issue is? 不确定是什么问题?

Your problem is that the AddRange method of the generic List class is declared as returning void. 您的问题是通用List类AddRange方法被声明为返回void。

Update : Edited to fix List<int> vs. IList<int> issue. 更新 :编辑以修复List<int>IList<int>问题。

You need to change it to: 您需要将其更改为:

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

Why not initialize the list with the results of your select query instead of doing AddRange since it takes IEnumerable as an overload: 为什么不使用选择查询的结果初始化列表而不是执行AddRange,因为它将IEnumerable作为重载:

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

AddRange doesn't return a list - it returns void. AddRange不返回列表-它返回void。 You can do this via the constructor for List<T> that takes an enumerable : 您可以通过采用一个可枚举的 List<T>的构造函数来实现:

string categoryIDList = Convert.ToString(reader["categoryIDList"]);

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

To have better understanding of what is going on, I created example below. 为了更好地了解发生了什么,我在下面创建了示例。 Solution should be based on 1. list.AddRange, 2. then reassigning list to something else: 解决方案应基于1. list.AddRange,2.然后将list重新分配给其他对象:

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);

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM