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

问题描述 投票:1回答:1

[我正在尝试为类型为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);,这在这种情况下违反了泛型的目的。

[当TValue被约束为TEnumerable且我从中调用的具体字典应该知道该类型时,编译器如何无法推断IEnumerable<TValue>类型?

c# generics compiler-errors extension-methods ienumerable
1个回答
1
投票

类型推断仅基于类型实参,而不是类型约束,如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界面可访问。

© www.soinside.com 2019 - 2024. All rights reserved.