字典<studenttype,list <student =“”>&gt;到IDictionary <studenttype,ilist <student =“”>&gt;?</studenttype,> </studenttype,>

时间:2011-05-17 10:42:17

标签: c# list dictionary ilist idictionary

请考虑以下代码:

class Student
{
}

enum StudentType
{
}

static void foo(IDictionary<StudentType, IList<Student>> students)
{   
}

static void Main(string[] args)
{
    Dictionary<StudentType, List<Student>> studentDict = 
                     new Dictionary<StudentType, List<Student>>();

    foo(studentDict);

    ...
}

有错误:

  

错误CS1503:参数'1':不能   转换自   'System.Collections.Generic.Dictionary&GT;'   至   'System.Collections.Generic.IDictionary&GT;'

有没有办法调用foo函数?

3 个答案:

答案 0 :(得分:6)

您可以使用Linq ToDictionary方法创建一个新字典,其中值的类型正确:

static void Main(string[] args)
{
  Dictionary<StudentType, List<Student>> studentDict = new Dictionary<StudentType, List<Student>>();
  var dicTwo = studentDict.ToDictionary(item => item.Key, item => (IList<Student>)item.Value);
  foo(dicTwo);
}

答案 1 :(得分:3)

您将使用正确的类型构建一个新字典,将旧数据复制到新字典中。

或者,您可以将原始字典更改为正确的类型。

无论哪种方式,不,你不能施放字典。

此限制的原因如下:

  1. 字典包含Student
  2. 类型的值
  3. 你可以有很多类型来实现IStudent
  4. 你给予演员字典的方法可能会尝试将另一个IStudent填入字典,即使它不是学生

答案 2 :(得分:0)

将studentDict的创建更改为:

Dictionary<StudentType, IList<Student>> studentDict = new Dictionary<StudentType, IList<Student>>();