我正在尝试为 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>
我打电话的具体字典应该知道类型吗?
最佳答案
类型推断仅基于类型参数,而不是类型约束,如 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/