我想写一个扩展方法,它可以在字典上工作,它的值是某种顺序.不幸的是,编译器似乎无法从我对该方法的使用中推断出泛型参数; 我需要明确指定它们.
public static void SomeMethod<TKey, TUnderlyingValue, TValue>
(this IDictionary<TKey, TValue> dict)
where TValue : IEnumerable<TUnderlyingValue> { }
static void Usage()
{
var dict = new Dictionary<int, string[]>();
var dict2 = new Dictionary<int, IEnumerable<string>>();
//These don't compile
dict.SomeMethod();
SomeMethod(dict); // doesn't have anything to do with extension-methods
dict2.SomeMethod(); // hoped this would be easier to infer but no joy
//These work fine
dict.SomeMethod<int, string, string[]>();
dict2.SomeMethod<int, string, IEnumerable<string>>();
}
Run Code Online (Sandbox Code Playgroud)
我意识到类型推断不是一门精确的科学,但我想知道是否有一些基本的"规则"我在这里缺失 - 我不熟悉规范的细节.