2009-10-07 108 views
0
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,我试图在上面指定它。不能隐式地将void类型转换为IList <int>

错误:

错误1无法隐式转换类型 '无效' 到 'System.Collections.Generic.IList'

不知道是什么问题?

回答

0

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

5

您的问题是AddRange method of the generic List class被声明为返回void。

更新:修改为修复List<int>IList<int>问题。

您需要将其更改为:

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

Arghh,IList的不支持的AddRange关系吗? c.CategoryIDList是IList类型 mrblah 2009-10-07 00:45:38

+0

是的,这不会按原样编译。 – 2009-10-07 01:02:08

+0

@homestead&Reed Copsey:对,对不起。简单的解决方案就是使用'List '类型的临时变量。看到我的编辑可能的解决方案。 – 2009-10-07 01:27:44

3

,因为它需要的IEnumerable作为超载为什么不初始化您的选择查询的,而不是做的AddRange的结果列表不返回一个列表 - 它返回void。你可以通过构造为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)) 
     ); 
} 
2

的AddRange:

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

有更好的了解是怎么回事,我创建了下面的例子。 解决方案应该是基于1 list.AddRange,2.然后重新分配名单别的东西:

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); 
相关问题