【问题标题】:Cast Dictionary<Key, Value> to IReadOnlyDictionary<Key, IValue>?将 Dictionary<Key, Value> 转换为 IReadOnlyDictionary<Key, IValue>?
【发布时间】:2019-07-10 06:07:39
【问题描述】:

我们可以轻松做到这一点:

List<Value> list;
IReadOnlyList<IValue> List => list;

但是我们怎样才能对 IReadOnlyDictionary 做同样的事情呢?

Dictionary<Key, Value> dict;
IReadOnlyDictionary<Key, IValue> Dict => dic; //impossible

【问题讨论】:

    标签: c# dictionary interface casting


    【解决方案1】:

    你不能,但是以 allocationsrehashing 为代价,你可以投射它:

    IReadOnlyDictionary<string, IValue> Dict 
       => dict.ToDictionary(x => x.Key, x => (IValue)x.Value);
    

    尽管您可能需要重新考虑您的问题。

    【讨论】:

    • 是的,我认为最好的选择是添加如下函数:IValue Get(Key key) => dict[key]
    【解决方案2】:

    这是因为IReadOnlyList 是协变的:

    public interface IReadOnlyList<out T> {...}
    

    IReadOnlyDictionary 不是:

    public interface IReadOnlyDictionary<TKey,TValue> {...}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-22
      • 2019-08-08
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      • 2021-10-27
      相关资源
      最近更新 更多