【发布时间】:2020-04-19 20:46:29
【问题描述】:
当我将 Dictionary<int, HashSet<int>> 分配给 IDictionary<int, IEnumerable<int>> 时,我收到以下错误:
编译错误(第 27 行,第 9 列):无法将类型“System.Collections.Generic.Dictionary>”隐式转换为“System.Collections.Generic.IDictionary>”。存在显式转换(您是否缺少演员表?)
错误很明显。缺少一个演员表。为什么我在这里需要演员表? Dictionary<T,U> 实现 IDictionary<T,U> 和 HashSet<T> 实现 IEnumerable<T>。
using System;
using System.Linq;
using System.Collections.Generic;
public class Program
{
public class A
{
public IDictionary<int, IEnumerable<int>> D { get; set; }
public IEnumerable<int> H { get; set; }
}
public static void Main()
{
var hashSet = new HashSet<int>{1,2,1};
var a = new A { H = hashSet };
PrintCollection(a.H);
var d = new Dictionary<int, HashSet<int>>{{ 3, hashSet }};
a.D = d; // error here
PrintCollection(a.D.First().Value);
}
public static void PrintCollection(IEnumerable<int> collections)
{
foreach (var item in collections)
Console.WriteLine(item);
}
}
【问题讨论】:
-
我建议阅读 C# 中的方差。
-
这是因为对于
IDictionary<TKey, TValue>,TValue不是协变的。 -
正如重复的 and Tom 的回答所解释的,您所问的内容不安全,因此被禁止。