请考虑以下代码:
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函数?
答案 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)
您将使用正确的类型构建一个新字典,将旧数据复制到新字典中。
或者,您可以将原始字典更改为正确的类型。
无论哪种方式,不,你不能施放字典。
此限制的原因如下:
答案 2 :(得分:0)
将studentDict的创建更改为:
Dictionary<StudentType, IList<Student>> studentDict = new Dictionary<StudentType, IList<Student>>();