【问题标题】:Dictionary<StudentType, List<Student>> to IDictionary<StudentType, IList<Student>>?字典<StudentType, List<Student>> 到 IDictionary<StudentType, IList<Student>>?
【发布时间】:2011-08-27 03:27:23
【问题描述】:

请考虑以下代码:

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 函数?

【问题讨论】:

  • 您实现了自己的集合?如果没有,看不出有任何理由避免使用static void foo(Dictionary&lt;StudentType, List&lt;Student&gt;&gt; students) 来解决这个问题。
  • static void foo(IDictionary&lt;StudentType, IList&lt;Student&gt;&gt; students) 只是为了简单。 IDictionary 不是foo(),而是传递给我的应用程序的另一部分,因此有必要使用IDictionary&lt;&gt;IList&lt;&gt; 来提供抽象。

标签: c# list dictionary ilist idictionary


【解决方案1】:

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

【讨论】:

  • 谢谢!这正是我所需要的。
【解决方案2】:

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

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

无论如何,不​​,你不能转换字典。

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

  1. 字典包含 Student 类型的值
  2. 您可以有许多实现 IStudent 的类型
  3. 您向已转换字典提供的方法可能会尝试将另一个 IStudent 填充到字典中,即使它不是学生也是如此

【讨论】:

  • 我不明白这个答案。问题中没有 IStudent。
【解决方案3】:

将studentDict的创建改为:

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

【讨论】:

  • 抱歉,这不是一个选项。我正是需要这个创作。
  • 你能解释一下为什么你需要这个创作吗?您可以将 List 添加到该创作中。如果您已经在代码的其他地方创建了对象,那么您需要通过创建新字典并转换值来转换它
  • 因为我需要在从字典中获取 List 特定的成员函数时调用它。
  • @ColinE 下面的答案将满足您的要求
猜你喜欢
  • 1970-01-01
  • 2016-04-19
  • 2013-01-18
  • 2021-12-02
  • 2016-11-17
  • 1970-01-01
  • 1970-01-01
  • 2019-06-02
  • 2023-03-23
相关资源
最近更新 更多