【问题标题】:return IDictionary<string, ICollection<ValueSet>>返回 IDictionary<string, ICollection<ValueSet>>
【发布时间】:2013-02-19 20:44:00
【问题描述】:

我正在尝试返回接口IDictionary(带有字符串键和列表值),例如:

IDictionary<string, ICollection<ValueSet>> method( ...) {

}

我从方法内部创建 Dictionary 对象:

var dic = new Dictionary <string, List <ValueSet> >();

一切正常,但我无法在此处返回 dic 对象。我不能隐式转换。

我怎样才能让这件事发挥作用?

public IDictionary < string, ICollection < ValueSet > > GetValueSets(ICollection < string > contentSetGuids)

{
    var dic = new Dictionary < string, List < ValueSet > > ();

    using (SqlCommand command = new SqlCommand())
    {
        StringBuilder sb = new StringBuilder(ValueSet.ValueSetQueryText);
        sb.Append(" where contentsetguid ");
        sb.Append(CreateInClause(contentSetGuids));

        command.CommandText = sb.ToString();

        dic = GetObjects(command).GroupBy(vs => vs.ContentSetGuid).ToDictionary(grp => grp.Key, grp => grp.ToList());

    }

    return dic;
}

错误: 错误 46 无法将类型“System.Collections.Generic.IDictionary>”隐式转换为“System.Collections.Generic.IDictionary>”。存在显式转换(您是否缺少演员表?)

【问题讨论】:

  • 这是什么语言?
  • C# ....................
  • 您能否更新您的问题以显示完整的方法以及完整的错误?

标签: c# collections


【解决方案1】:

您不能将IDictionary&lt;String, List&lt;ValueSet&gt;&gt; 转换为IDictionary&lt;String, ICollection&lt;ValueSet&gt;&gt;,因为IDictionary&lt;TKey, TValue&gt; 不是covariant。例如,IEnumerable&lt;T&gt; 接口协变的,因此您可以根据需要将IEnumerable&lt;List&lt;ValueSet&gt;&gt; 转换为IEnumerable&lt;ICollection&lt;ValueSet&gt;&gt;

但是,您可以通过在方法中创建正确类型的字典来解决您的问题。例如:

public IDictionary<string, ICollection<ValueSet>> GetValueSets(
    ICollection<ValueSet> contentSetGuids)
{
    var dic = new Dictionary<string, ICollection<ValueSet>>();   // <--

    using (SqlCommand command = new SqlCommand())
    {
        // ...
        dic = GetObjects(command)
              .GroupBy(vs => vs.ContentSetGuid)
              .ToDictionary(
                  grp => grp.Key,
                  grp => (ICollection<ValueSet>)grp.ToList());   // <--
    }

    return dic;
}

【讨论】:

    【解决方案2】:

    我会考虑将界面更改为更灵活:

    IEnumerable<KeyValuePair<string, IEnumerable<ValueSet>> GetValueSets(
        IEnumerable<ValueSet> contentSetGuids)
    
    {
        // ....
        return GetObjects(command)
            .GroupBy(vs => vs.ContentSetGuid)
            .Select(new KeyValuePair<string, IEnumerable<ValueSet>>(grp.Key, grp.ToArray())
    }
    

    让调用者创建一个字典,它需要一个。

    通常 我会将字符串(键)作为参数传递,并且一次只返回一个元素。但是在该方法中,您一次获得了全部数据,所以这没有多大意义。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-24
      • 2010-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多