简体   繁体   English

C#泛型 - 为什么lambda工作,简单方法不工作?

[英]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-in​​ference-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.

相关问题 为什么C#不对泛型做“简单”类推理? - Why doesn't C# do “simple” type inference on generics? C#中的Unicode类名 - 为什么有些工作,有些则不工作? - Unicode class names in C# - why do some work, when others don't? 简单的协方差似乎不适用于c#泛型 - Simple Covariance doesn't seem to work with c# generics 为什么 C# 不接受带有 generics 参数的构造函数要求? - Why C# don't accept constructor requirements with parameters on generics? C#:为什么当我们不指定泛型时,泛型不使用它可以使用的最泛型类型? - C#: Why don't generics use the most generic type it can when we don't specify one? 为什么python中的相对路径在从C#运行时不起作用,但在c#之外使用相同的解释器时是否有效? - Why relative paths in python don't work when run from C#, but do work when using the same interpreter outside of c#? C#重构函数以使用泛型和Lambda - C# Refactor function to use generics and lambdas 在 C++ 工作,但不在 C# 工作,我不知道为什么 - Do while work in C++ but not in C# and i don't know why C# lambda 如何在没有“返回”的情况下工作? - How do C# lambdas work without a “return”? 为什么我在表格上绘制的方法不起作用? ( C# ) - Why do my methods to draw on a form not work? ( C# )
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM