Cannot implicitly convert type void to IList

2019-08-31 17:44发布

问题:

 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?

回答1:

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;


回答2:

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


回答3:

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:

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


回答5:

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



标签: c# oop