如何将类型“System.Collections.Generic.Dictionary>”隐式转换为“System.Collections.Generic.IDictionary>”?

alo*_*ica 0 c# oop

当我将 a 分配Dictionary<int, HashSet<int>>给 a 时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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在线试用!

Tom*_*m W 5

你不能。如果您采用一个类型的变量IDictionary<int, IEnumerable<int>>并尝试添加 say anIList<int>作为值 - 根据变量的类型,您应该能够做到 - 那么在您的情况下,实际上需要向您的Dictionary<int, HashSet<int>>. 你不能强制转换这个类型,因为那会使用类型系统来表达一些不正确的东西——任何IEnumerable<int>都可以添加到字典中——它不能。