虽然智能感知列出它找不到的定义? [英] Cannot find definition though intellisense lists it?
问题描述
我得到与Visual Studio 10(现在11以及)一个奇怪的错误。我有一个扩展方法
I'm getting a strange error with Visual Studio 10 (and now 11 as well). I have an extension method
public static S Foo<S, T>(this S s) where S : IEnumerable<T>
{
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?)
我并不理解什么是引擎盖下发生的。恼人的是,在智能感知列表富
为 IEnumberable< T>
取值。 。在最好的情况应该都给予了类型无法推断错误
I'm not at all understanding what's happening under hood. The annoying part is that the intellisense lists Foo
for IEnumberable<T>
s. At best it should have given a type can't be inferred error
.
如果我把它称为是这样的:
If I call it this way:
Extension.Foo(""); // => The type arguments for method 'Extension.Foo<S,T>(S)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
为什么不能类型在上述情况下,可以推断?
更多:
假设我有:
public static S Foo<S, T>(this S s, T t) where S : IEnumerable<T>
{
return s;
}
如果我称之为:
And if I call:
"".Foo(1);
该类型推断是如此的聪明在这里告诉我, 富
应该返回的IEnumerable< INT>
和字符串
是不是所有的!
The type inference is so smart here to tell me that Foo
should be returning IEnumerable<int>
and string
is not all that!!
因此,如果编译器能够知道富
期待一个字符作为第一个参数,那么为什么不我的第一个例子只是编译? 换句话说这是为什么在第一个例子,编译器知道 T
在这种情况下为char?
So if compiler can know Foo
is expecting a char as the first argument, then why doesn't my first example just compile? In other words why is that in the first example the compiler know T
in that case is char?
由于果然这个工程的第二个例子:
As expectedly this works for the second example:
"".Foo('l');
我只是想知道为什么不能 T
被推断为字符
在第一个例子,毕竟字符串 IEnumberable<焦炭方式>
I'm just wondering why can't T
be inferred as char
in first example, after all string is IEnumberable<char>
.
我从SLaks答案。但它是如此奇怪的是C#不这样做(种类型推断的)考虑公开可用的方法在对象上进行操作时,编译器需要考虑的一般限制为好。
I got the answer from SLaks. But it's so strange that C# doesn't do this (kind of type inference) considering compiler takes into account the generic constraints as well when exposing the available methods to operate on an object.
在换句话说:
public static S Foo<S, T>(this S s)
{
return s;
}
让富
可用。所有的对象
取值
public static S Foo<S, T>(this S s) where S : IEnumerable<T>
{
return s;
}
让富
可用在所有的IEnumerable< T>
取值,因为它知道 取值
是的IEnumerable< T>
。所以我想C#仍会被推断 T
的类型!感谢大家! ;)
makes Foo
available on all IEnumerable<T>
s since it knows S
is IEnumerable<T>
. So I was thinking C# will be even inferring the type of T
! Thanks everyone! ;)
推荐答案
类型推理引擎是不够聪明做
The type inference engine isn't smart enough to do that.
C#类型推断只看该方法的签名的。结果
的通用约束不是签名的一部分。
C# type inference only looks at the method signature.
Generic constraints are not part of the signature.
由于 T
不签名直接使用,编译器将无法推断它。
Since T
is not used directly in the signature, the compiler will not infer it.
这篇关于虽然智能感知列出它找不到的定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!