为什么Dictionary <T1,List <T2 >>不能转换为Dictionary <T1,IEnumerable <T2 >>?

J C*_*per 3 .net c# generics collections casting

我想知道为什么我不能只是演员(我有一个模糊的想法,这可能与那个共同/逆转的东西有关?),我被迫将第一个字典的元素复制到新的字典中得到我想要的类型?

Jam*_*are 10

你不能这样做,因为它们不是同一类型.考虑:

        var x = new Dictionary<string, List<int>>();

        // won't compile, but assume it could...
        Dictionary<string, IEnumerable<int>> xPrime = x;

        // uh oh, would allow us to legally add array of int!
        xPrime["Hi"] = new int[13];
Run Code Online (Sandbox Code Playgroud)

这有意义吗?由于Dictionary<string, List<int>>该说TValue就是List<int>这意味着你可以Add()一个List<int>一个的值.如果你施放此为Dictionary<string, IEnumerable<int>>这将意味着值类型是IEnumerable<int>这将意味着你可以Add() 任意 IEnumerable<int>(int[],HashSet<int>,等),这将违背原来的类型.

因此,a List<T>可以转换为IEnumerable<T>引用,因为List<T>实现IEnumerable<T>,但这并不意味着Dictionary<TKey, List<TValue>>实现/扩展Dictionary<TKey, IEnumerable<TValue>>.

更简单地说:

Dictionary<int, Dog> 
Run Code Online (Sandbox Code Playgroud)

无法转换为

Dictionary<int, Animal>
Run Code Online (Sandbox Code Playgroud)

因为后者会允许你添加Cat,Squirrel等.