Cannot implicitly convert type void to IList

2019-08-31 17:51发布

 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.

Error:

Error 1 Cannot implicitly convert type 'void' to 'System.Collections.Generic.IList'

Not sure what the issue is?

标签: c# oop
5条回答
冷血范
2楼-- · 2019-08-31 18:18

You're assigning the result of AddRange to c.CategoryIDList, not the new list itself.

查看更多
迷人小祖宗
3楼-- · 2019-08-31 18:19

AddRange doesn't return a list - it returns void. You can do this via the constructor for List<T> 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楼-- · 2019-08-31 18:26

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:

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);
查看更多
▲ chillily
5楼-- · 2019-08-31 18:28

Why not initialize the list with the results of your select query instead of doing AddRange since it takes IEnumerable as an overload:

c.CategoryIDList = new List<int>(categoryIDList.Split(',')
 .Select(s => Convert.ToInt32(s)));
查看更多
Viruses.
6楼-- · 2019-08-31 18:31

Your problem is that the AddRange method of the generic List class is declared as returning void.

Update: Edited to fix List<int> vs. IList<int> issue.

You need to change it to:

List<int> foo = new List<int>();
foo.AddRange(
    categoryIDList 
    .Split(',')
    .Select(s => Convert.ToInt32(s)));
c.CategoryIDList = foo;
查看更多
登录 后发表回答