繁体   English   中英

编译器无法从包装的通用 IEnumerable 推断类型

[英]Compiler cannot infer type from wrapped generic IEnumerable

我正在尝试为类型为Dictionary<TKey, IEnumerable<TValue>>的字典编写通用扩展方法,该方法应该返回给定键的IEnumerable<TValue>实例,如果该键还没有条目,则创建一个IEnumerable<TValue>新实例并为该键添加它。

public static TEnumerable GetAndEnsureEnumerableForKey<TKey, TValue, TEnumerable>(
  this Dictionary<TKey, TEnumerable> dictionary, TKey key)
    where TEnumerable : IEnumerable<TValue> 
{
  TEnumerable enumerableForKey;
  if (!dictionary.TryGetValue(key, out enumerableForKey)) 
  {
    Type enumerableType = typeof(TEnumerable);
    enumerableForKey = (TEnumerable)Activator.CreateInstance(enumerableType);
    dictionary.Add(key, enumerableForKey);
  }

  return enumerableForKey;
}

该方法本身工作正常,但我对该方法的调用有问题。 给定一个Dictionary<int, List<int>> intListDictionary我希望调用intListDictionary.GetAndEnsureEnumerableForKey(sampleInt); 工作得很好。 但是编译器抱怨它无法从方法调用中推断出TValue类型,我将不得不调用intListDictionary.GetAndEnsureEnumerableForKey<int, int, List<int>>(sampleInt); 在这种情况下,哪种类型违背了泛型的目的。

TEnumerable约束为IEnumerable<TValue>并且我正在调用的具体字典应该知道类型时,编译器如何无法推断类型TValue

类型推断仅基于类型参数,而不是类型约束,如本答案中所述

为了实现您想要的,您可以将TEnumerable的类型约束更改为非通用IEnumerable接口:

public static TEnumerable GetAndEnsureEnumerableForKey<TKey, TEnumerable>(
    this Dictionary<TKey, TEnumerable> dictionary,
    TKey key)
    where TEnumerable : IEnumerable
{
    TEnumerable enumerableForKey;
    if (!dictionary.TryGetValue(key, out enumerableForKey))
    {
        Type enumerableType = typeof(TEnumerable);
        enumerableForKey = (TEnumerable)Activator.CreateInstance(enumerableType);
        dictionary.Add(key, enumerableForKey);
    }

    return enumerableForKey;
}

您需要添加System.Collections以使IEnumerable接口可访问。

暂无
暂无

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

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