[英]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)));
}
该类具有一个IList CategoryIDList属性,我正在尝试将其分配给该属性。
错误:
错误1无法将类型'void'隐式转换为'System.Collections.Generic.IList'
不确定是什么问题?
您的问题是通用List类的AddRange方法被声明为返回void。
更新 :编辑以修复List<int>
与IList<int>
问题。
您需要将其更改为:
List<int> foo = new List<int>();
foo.AddRange(
categoryIDList
.Split(',')
.Select(s => Convert.ToInt32(s)));
c.CategoryIDList = foo;
为什么不使用选择查询的结果初始化列表而不是执行AddRange,因为它将IEnumerable作为重载:
c.CategoryIDList = new List<int>(categoryIDList.Split(',')
.Select(s => Convert.ToInt32(s)));
AddRange不返回列表-它返回void。 您可以通过采用一个可枚举的 List<T>
的构造函数来实现:
string categoryIDList = Convert.ToString(reader["categoryIDList"]);
if (!String.IsNullOrEmpty(categoryIDList))
{
c.CategoryIDList =
new List<int>(
categoryIDList.Split(',').Select(s => Convert.ToInt32(s))
);
}
为了更好地了解发生了什么,我在下面创建了示例。 解决方案应基于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.