[英]C# generics — why do lambdas work, when simple methods don't?
I'm having trouble understanding why the C# compiler can infer types for 我无法理解为什么C#编译器可以推断出类型
Array.ConvertAll(new int[1], i => Convert.ToDouble(i));
but not for 但不是
Array.ConvertAll(new int[1], Convert.ToDouble);
when it would seem that the former would be a more complicated deduction than the latter. 当看起来前者比后者更复杂的推论时。
Could someone please explain why this happens? 有人可以解释为什么会这样吗?
This issue is pretty well covered in this (archived) blog post: http://blogs.msdn.com/b/ericlippert/archive/2007/11/05/c-3-0-return-type-inference-does-not-work-on-member-groups.aspx 此(已存档)博客文章中详细介绍了此问题: http : //blogs.msdn.com/b/ericlippert/archive/2007/11/05/c-3-0-return-type-inference-does-不工作-ON-成员groups.aspx
In summary as I understand it (should the link ever vanish); 总而言之,据我了解(链接是否应该消失); this was a conscious design decision in C# 3.0, in that it was not appropriate to perform type inference on Method Groups (your second example). 这是C#3.0中有意识的设计决策,因为它不适合在方法组(第二个例子)上执行类型推断。
I guess quite a few folks didn't like that, so the issue was resolved for C# 4.0 (as of Visual Studio 2010); 我想很多人都不喜欢这样,所以C#4.0解决了这个问题(从Visual Studio 2010开始);
"In C# 4.0, return type inference works on method group arguments when the method group can be associated unambiguously with a completely fixed set of argument types deduced from the delegate. Once the argument types associated with the method group are known, then overload resolution can determine unambiguously which method in the method group is the one associated with the delegate formal parameter; we can then make a return type inference from the specific method to the delegate return type." “在C#4.0中,当方法组可以明确地与从委托推导出的一组完全固定的参数类型相关联时,返回类型推断对方法组参数起作用。一旦与方法组关联的参数类型已知,则重载解析可以明确地确定方法组中哪个方法是与委托形式参数相关联的方法;然后我们可以从特定方法到委托返回类型进行返回类型推断。“
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.