【问题标题】:C# IDictionary with ICollection values without exposing implementation details具有 ICollection 值的 C# IDictionary 而不暴露实现细节
【发布时间】:2013-12-04 06:35:22
【问题描述】:

我正在使用某种集合类型的值设置一个字典,如下所示:

IDictionary<string, ICollection<decimal>> goodPrices = 
    new Dictionary<string, List<decimal>>();

但是,这行代码会导致无法将右侧隐式转换为左侧的编译错误。显然,以下行不会产生错误:

IDictionary<string, List<decimal>> goodPrices = 
    new Dictionary<string, List<decimal>>();

那么在不暴露集合的底层实现的情况下,将“goodPrices”声明为一组字符串-集合对的正确方法是什么?

【问题讨论】:

  • 您可以随时使用new Dictionary&lt;string, ICollection&lt;decimal&gt;&gt;(),然后将Lists 分配给字典键,例如goodPrices["test"] = new List&lt;decimal&gt; { 3.30m };...

标签: c# generics collections covariance


【解决方案1】:

这个呢:

IDictionary<string, ICollection<decimal>> goodPrices = new Dictionary<string, ICollection<decimal>>();
goodPrices.Add("myString", new List<decimal>() { /* my values */ });

【讨论】:

  • 啊,当然!您的答案和@Patryk 都是要走的路。我后来发现了以下关于隐式转换失败的根本原因的 SO 帖子:link
猜你喜欢
  • 2011-02-17
  • 2016-03-05
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
  • 2016-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多