Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法将类型void隐式转换为IList_C#_Oop - Fatal编程技术网

C# 无法将类型void隐式转换为IList

C# 无法将类型void隐式转换为IList,c#,oop,C#,Oop,该类有一个属性IList CategoryIDList,我正试图分配给上面的属性 错误: 错误1无法将类型“void”隐式转换为“System.Collections.Generic.IList” 不确定问题出在哪里?您正在将AddRange的结果分配给c.CategoryIDList,而不是新列表本身。您的问题是该列表被声明为返回void 更新:编辑以修复列表与IList问题 您需要将其更改为: string categoryIDList = Convert.ToString(reader[

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

错误:

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


不确定问题出在哪里?

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

您的问题是该列表被声明为返回void

更新:编辑以修复列表与IList问题

您需要将其更改为:

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

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

    }

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

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

AddRange不返回列表-它返回void。您可以通过列表的构造函数执行此操作:


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

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

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

Arghh,但IList不支持AddRange?c、 CategoryIDList是IListies类型,无法按原样编译。@homestead&Reed Copsey:是的,很抱歉。简单的解决方案就是使用List类型的临时变量。请参阅我的编辑以了解一种可能的解决方案。
string categoryIDList = Convert.ToString(reader["categoryIDList"]);

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