5

请考虑以下代码:

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>”转换为“System.Collections.Generic.IDictionary>”

有没有办法调用 foo 函数?

4

3 回答 3

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);
}
于 2011-05-17T10:49:00.487 回答
3

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

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

无论哪种方式,不,您不能转换字典。

造成这种限制的原因如下:

  1. 字典包含 Student 类型的值
  2. 您可以有许多实现 IStudent 的类型
  3. 您提供已转换字典的方法可能会尝试将另一个 IStudent 填充到字典中,即使它不是 Student
于 2011-05-17T10:46:21.243 回答
0

将 studentDict 的创建更改为:

Dictionary<StudentType, IList<Student>> studentDict = new Dictionary<StudentType, IList<Student>>();
于 2011-05-17T10:47:34.717 回答