c#字典键/值可枚举类型与数组/列表不兼容



我有下面一段代码,它抛出错误:

不能隐式转换类型"System.Collections.Generic"。字典>"System.Collections.Generic。字典>的

我希望编译器理解IEnumerableList是兼容的,但它抛出错误。请解释一下为什么会这样?

Dictionary<string, List<DataRow>> sampleData = new Dictionary<string, List<DataRow>>();
                Dictionary<string, IEnumerable<DataRow>> schedules = sampleData;

谢谢!

问题是Dictionary不是协变的,所以你不能为它的泛型参数使用派生较少的类型。

假设您的代码已编译,那么您可以这样做:

Dictionary<string, List<DataRow>> sampleData = 
    new Dictionary<string, List<DataRow>>();
Dictionary<string, IEnumerable<DataRow>> schedules = sampleData;
schedules["KeyOne"] = new DataRow[] {null};   
// should fail since an array is not a list, and the object type requires a list.

一个变通办法是

Dictionary<string, IEnumerable<DataRow>> schedules = 
       sampleData.ToEnumerableDic();

带有泛型扩展名

public static Dictionary<T1, IEnumerable<T2>> ToEnumerableDic<T1,T2>(this Dictionary<T1, List<T2>> sampleData) {
    return sampleData.Select(x => new { a = x.Key, b = x.Value.AsEnumerable() })
        .ToDictionary(x => x.a, x => x.b);
}

最新更新