luc*_*uke 2 c# generics type-inference
嗨,我很难做C#类型推断做我想要的.我有一个非常特殊的情况,我有很多变量的味道
ConcurrentDictionary<T, IDictionary<U, V> >
Run Code Online (Sandbox Code Playgroud)
其中T,U,V可以是一些随机类型,如long,int或其他类型.
我想编写适用于这类变量的方法 - 特别是检查它们的直方图.
所以我写了一个方法
public static IOrderedEnumerable<Tuple<int,int>> GetDictionaryHistogram<T, U, V, W>(T dictionary) where T : ConcurrentDictionary<U, IDictionary<V, W>>
{
return dictionary.Select(p => p.Value.Count)
.GroupBy(p => p)
.Select(p => new Tuple<int, int>(p.Key, p.Count()))
.OrderBy(p => p.Item1);
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试调用它时,C#给出了一个错误,它无法推断出类型.例如,对类型的变量
ConcurrentDictionary<int,IDictionary<int, int> > foo;
Run Code Online (Sandbox Code Playgroud)
我收到错误:
错误118无法从用法中推断出方法"Auditor.AuditorHelpers.GetDictionaryHistogram(T)"的类型参数.尝试显式指定类型参数.
我做错了什么?
类型推断从参数到形式参数类型推断.没有对约束进行推论,因为约束不是方法签名的一部分.
在您的情况下,类型推断必须始终失败; 类型推断不可能推断U和V的类型,因为它们不出现在形式参数类型中.
大约有十几个人告诉我,我认为这个规则是明智的是错误的,请参阅我关于这个主题的文章的评论.