【问题标题】:C# Dictionary Key/Value Ienumerable type not compatiable with Array/List [duplicate]C#字典键/值可枚举类型与Arraylist不兼容[重复]
【发布时间】:2016-09-08 14:04:46
【问题描述】:

我有以下代码,它会抛出错误:

无法将类型“System.Collections.Generic.Dictionary>”隐式转换为 'System.Collections.Generic.Dictionary>'

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

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

谢谢!

【问题讨论】:

  • Lists 和 Ienums 兼容但不一样,需要强制转换或更改为相同
  • 我不认为字典是共同变量

标签: c#


【解决方案1】:

问题在于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.

【讨论】:

    【解决方案2】:

    解决方法可能是

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多