简单的 Linq 表达式无法编译
有了这些基本定义,
bool MyFunc(string input)
{
return false;
}
var strings = new[] {"aaa", "123"};
我想知道为什么这不会编译:
var b = strings.Select(MyFunc);
但这会:
var c = strings.Select(elem => MyFunc(elem));
错误消息是“方法 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System) 的类型参数.Func)' 无法从用法中推断出来。”
Resharper 错误提示表示它混淆了
Select(this IEnumerable<string>, Func<string, TResult>)
和
Select(this IEnumerable<string>, Func<string, int, TResult>)
...但 MyFunc 的签名很清楚 - 它只需要一个(字符串)参数。
任何人都可以在这里阐明一些情况吗?
Having these basic definitions
bool MyFunc(string input)
{
return false;
}
var strings = new[] {"aaa", "123"};
I'm wondering why this won't compile :
var b = strings.Select(MyFunc);
But this will:
var c = strings.Select(elem => MyFunc(elem));
The error message is "The type arguments for method 'System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable, System.Func)' cannot be inferred from the usage."
The Resharper error tip says it's confused between
Select(this IEnumerable<string>, Func<string, TResult>)
and
Select(this IEnumerable<string>, Func<string, int, TResult>)
...but the signature for MyFunc is clear - it just takes one (string) parameter.
Can anyone shed some light here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C# 3 和 C# 4 编译器之间的泛型类型推断在实现方面略有变化。下面是一个简短但完整的示例程序:
它使用 .NET 4 中的 C# 编译器进行编译,但不能使用 .NET 3.5 中的编译器进行编译。
我认为将其称为错误修复是合理的,因为我不认为这是规范更改。
如果您必须使用 .NET 3.5 中的编译器,您可以添加强制转换来澄清:
或者
您可以使类型参数显式化:
Generic type inference changed slightly - in terms of implementation - between the C# 3 and C# 4 compiler. Here's a short but complete example program:
That compiles with the C# compiler in .NET 4, but not the one in .NET 3.5.
I think it's reasonable to call this a bug fix, as I don't think it was a spec change.
If you have to use the compiler from .NET 3.5, you can add a cast to clarify:
or
or you could make the type argument explicit:
乔恩当然像往常一样是正确的。一些附加信息:
这是 2007 年的博客文章,我在其中描述了您遇到的问题:
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 出于调度原因。
几个月后,我宣布修复将进入 C# 4,而不是 C# 3 服务包:
http://blogs.msdn.com/b/ericlippert/archive/2008/05/28/method-type-inference-changes -part-zero.aspx
Jon is of course correct as usual. Some additional information:
Here's the blog article from 2007 where I describe the problem you're having:
http://blogs.msdn.com/b/ericlippert/archive/2007/11/05/c-3-0-return-type-inference-does-not-work-on-member-groups.aspx
Based on the feedback on that article we decided to fix this, but could not get the fix into C# 3 for scheduling reasons.
A few months after that I announced that the fix would go into C# 4, not into the C# 3 service pack:
http://blogs.msdn.com/b/ericlippert/archive/2008/05/28/method-type-inference-changes-part-zero.aspx