C#泛型 - 为什么lambda表达式的工作,当简单的方法没有? [英] C# generics -- why do lambdas work, when simple methods don't?

查看:175
本文介绍了C#泛型 - 为什么lambda表达式的工作,当简单的方法没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解为什么C#编译器可以推断类型

I'm having trouble understanding why the C# compiler can infer types for

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?

推荐答案

此问题是很好覆盖在这个(存档)博客文章:的 http://blogs.msdn.com/b/ericlippert/archive/2007/11/05/c-3-0-return-type-in​​ference-does-not-工作-ON-成员groups.aspx

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

在我的理解是(应该链接永远消失)摘要;这是一种有意识的设计决定在C#3.0,因为它是不恰当的方法上组(你的第二个例子)执行类型推断。

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#4.0(如Visual Studio 2010中的);

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中,返回类型推断工作在方法组参数时,方法组可以明确地用一个完全固定的一套从委托推断参数类型相关联。一旦参数类型与方法相关组是已知的,那么重载可以明确确定哪种方法的方法组与委托形式参数相关联的一个;然后,我们可以从具体的方法为委托返回类型的返回类型推断

"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#泛型 - 为什么lambda表达式的工作,当简单的方法没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆