我有这个代码(为了清楚起见,最小化):
interface IEither<out TL,out TR> { } class Left<TL,TR> : IEither<TL,TR> { public Left(TL value) { } } static class Either { public static IEither<TL,TR> Left<TL,TR> (this TL left) { return new Left<TL,TR> (left); } }
为什么我不能说:
static class Foo { public static IEither<string,int> Bar () { //return "Hello".Left (); // Doesn't compile return "Hello".Left<string,int> (); // Compiles } }
我收到一个错误,指出’string’不包含’Left’的定义,并且没有扩展方法’Left’接受’string’类型的第一个参数可以被找到(你缺少using指令或程序集引用吗? (CS1061).
解决方法
我建议您看看C#规范中的7.5.2节.
7.5.2 Type inference
When a generic method is called without specifying type arguments,a
type inference process attempts to infer type arguments for the call.
The presence of type inference allows a more convenient Syntax to be
used for calling a generic method,and allows the programmer to avoid
specifying redundant type information.[…]
Type inference occurs as part of the binding-time processing of a method invocation (§7.6.5.1) and takes place before the overload resolution step of the invocation […]
那么在任何类型的重载分辨率完成之前,分辨率就会发生,问题在于推断出你所说的类型甚至没有被尝试,而且坦白地说也不总是可能的.
通用类型的参数的类型解析只能通过调用中的参数完成!在你的例子中只有一个字符串!它不能从参数中推断出int,只能在通用类型解析时解析的调用上下文.