[英]Why does the compiler not infer the generic type
I have the following method:我有以下方法:
public static void Foo<T>(Predicate<T> validator) { ... }
And I want to call it the following way:我想这样称呼它:
Foo(s => string.IsNullOrEmpty(s));
Why can't the compiler figure out s
is string
and therefore T
is string
?为什么编译器不能确定
s
是string
,因此T
是string
? What rule in the spec makes the inference algorithm fail here?规范中的什么规则使推理算法在这里失败?
I admit I haven't checked the entire C# 5.0 specification, but section 8.5.1 Local variable declarations talks a bit about the var
keyword, which is used to declare an inferred type.我承认我没有检查整个 C# 5.0 规范,但是8.5.1 局部变量声明部分谈到了
var
关键字,它用于声明推断类型。
Here are the rules for variables declared for var
and for all inferred variables:以下是为
var
和所有推断变量声明的变量的规则:
Because this is a lambda, your inferred initializer is:因为这是一个 lambda,所以您推断的初始化程序是:
string.IsNullOrEmpty(s)
OK, so...好的,那么...
So, to answer your question, your initializer ultimately fails because its type must be known before you can pass it to a method.因此,为了回答您的问题,您的初始化程序最终会失败,因为在将其传递给方法之前必须知道其类型。
Lambdas can fix this relatively easily, though:不过,Lambda 可以相对轻松地解决这个问题:
Foo(string s => string.IsNullOrEmpty(s));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.