gpt4 book ai didi

c# - Dictionary> 到 IDictionary>?

转载 作者:太空狗 更新时间:2023-10-29 22:34:14 25 4
gpt4 key购买 nike

请考虑以下代码:

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);

...
}

出现错误:

error CS1503: Argument '1': cannot convert from 'System.Collections.Generic.Dictionary>' to 'System.Collections.Generic.IDictionary>'

有什么方法可以调用foo函数吗?

最佳答案

您可以使用 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);
}

关于c# - Dictionary<StudentType, List<Student>> 到 IDictionary<StudentType, IList<Student>>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6029654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com