虽然intellisense列出了找不到定义吗?
我在Visual Studio 10中遇到了一个奇怪的错误(现在也是11)。 我有一个扩展方法
public static S Foo(this S s) where S : IEnumerable { return s; }
现在,如果我打电话
"".Foo(); // => 'string' does not contain a definition for 'Foo' and no extension method 'Foo' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
我根本不了解引擎盖下发生了什么。 烦人的部分是intellisense列出了对于IEnumberable
的Foo
。 充其量它应该给出一个type can't be inferred error
。
如果我这样称呼它:
Extension.Foo(""); // => The type arguments for method 'Extension.Foo(S)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
为什么不能在上述情况下推断出类型?
更多:
假设我有:
public static S Foo(this S s, T t) where S : IEnumerable { return s; }
如果我打电话:
"".Foo(1);
这里的类型推断是如此聪明,告诉我Foo
应该返回IEnumerable
并且string
不是全部!
因此,如果编译器可以知道Foo
期望将char作为第一个参数,那么为什么我的第一个例子不能编译? 换句话说,为什么在第一个例子中编译器知道T
在这种情况下是char?
正如预期的那样,这适用于第二个例子:
"".Foo('l');
我只是想知道为什么在第一个例子中不能将T
推断为char
,毕竟string是IEnumberable
。
编辑:
我从SLaks那里得到了答案。 但是奇怪的是,C#没有这样做(类型推断),考虑到编译器在暴露可用的方法来操作对象时也考虑了generics约束。
换一种说法:
public static S Foo(this S s) { return s; }
使Foo
适用于所有object
。
public static S Foo(this S s) where S : IEnumerable { return s; }
使Foo
在所有IEnumerable
上可用,因为它知道 S
是IEnumerable
。 所以我认为C#甚至会推断T
的类型! 感谢大家! ;)
类型推理引擎不够智能。
C#类型推断仅查看方法签名 。
通用约束不是签名的一部分 。
由于T
不直接在签名中使用,编译器不会推断它。