简体   繁体   English

无法从非协变通用接口隐式转换类型

[英]Cannot implicitly convert type from non-covariant generic interface

Important edit : Do not use a Dictionary in this context. 重要编辑 :请勿在此上下文中使用词典。 It uses Object.GetHashCode() which isn't good for use as a dictionary key. 它使用Object.GetHashCode(),它不适合用作字典键。 I still learned something from this though. 我仍然从中学到了一些东西。

I have the following declaration 我有以下声明

private static IDictionary<IDictionary<string,string>, IEnumerable<Fishtank>> _cache;

and the following code to attempt to initialize it 和以下代码尝试初始化它

if (_cache == null) 
  _cache = new Dictionary<Dictionary<string,string>, LinkedList<Fishtank>>(); 

The problem I'm having is the initialization generates a compile time error. 我遇到的问题是初始化会产生编译时错误。

Cannot implicitly convert type 'System.Collections.Generic.Dictionary,System.Collections.Generic.LinkedList>' to 'System.Collections.Generic.IDictionary,System.Collections.Generic.IEnumerable>'. 无法将类型'System.Collections.Generic.Dictionary,System.Collections.Generic.LinkedList>'隐式转换为'System.Collections.Generic.IDictionary,System.Collections.Generic.IEnumerable>'。 An explicit conversion exists (are you missing a cast?) 存在显式转换(您是否错过了演员?)

I know that Dictionary and LinkedList implement IDictionary and IEnumerable respectively, so I'm at a bit of a loss here. 我知道Dictionary和LinkedList分别实现了IDictionary和IEnumerable,所以我在这里有点不知所措。

you can do as below 你可以这样做

if (_cache == null) 
    _cache = new Dictionary<IDictionary<string, string>, IEnumerable<Fishtank>>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM