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

标签 c# generics compiler-errors extension-methods 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);在这种情况下,哪种方式违背了泛型的目的。

编译器怎么无法推断类型TValueTEnumerable被约束为 IEnumerable<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接口(interface)可访问。

关于c# - 编译器无法从包装的通用 IEnumerable 推断类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60974685/

相关文章:

c# - 如何在 C# 中的 Nhibernate 中传递两个连接字符串?

Java:在此设计中使用泛型的替代方案是什么?

c# - 使用反射将通用列表的实例添加到对象

c++ - CodeLite - 控制台运行但代码不工作

Java,如何使用 computeIfAbsent computeIfPresent 来实现这个目的?

c# - 如果不存在,EF7 sqlite 创建表

c# - 在查询中使用文本值

Swift:将泛型类型限制为闭包

java - StringUtils.isNumeric 是未定义的方法

c# - 可选属性默认值的 XML 序列化