为什么C#编译器不能为返回值推断类型参数?

前端之家收集整理的这篇文章主要介绍了为什么C#编译器不能为返回值推断类型参数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这个代码(为了清楚起见,最小化):
  1. interface IEither<out TL,out TR> {
  2. }
  3.  
  4. class Left<TL,TR> : IEither<TL,TR> {
  5. public Left(TL value) { }
  6. }
  7.  
  8. static class Either {
  9. public static IEither<TL,TR> Left<TL,TR> (this TL left) {
  10. return new Left<TL,TR> (left);
  11. }
  12. }

为什么我不能说:

  1. static class Foo
  2. {
  3. public static IEither<string,int> Bar ()
  4. {
  5. //return "Hello".Left (); // Doesn't compile
  6. return "Hello".Left<string,int> (); // Compiles
  7. }
  8. }

我收到一个错误,指出’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,只能在通用类型解析时解析的调用上下文.

猜你在找的C#相关文章