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

Compiler cannot infer type from wrapped generic IEnumerable

我正在尝试为 Dictionary<TKey, IEnumerable<TValue>> 类型的字典编写通用扩展方法,如果没有条目,应该 return 给定键的 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

类型推断仅基于类型参数,而不是类型约束,如 this answer 中所述。

要实现您想要的效果,您可以将 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 界面可访问。