简单的LINQ EX pression不会编译简单、LINQ、pression、EX

2023-09-07 03:42:54 作者:傲娇少女

有了这些基本的定义

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));

该错误消息的的类型参数的方法System.Linq.Enumerable.Select(System.Collections.Generic.IEnumerable,System.Func)不能从使用中推断出来。的

ReSharper的错误提示说,它

The Resharper error tip says it's confused between

Select(this IEnumerable<string>, Func<string, TResult>)

Select(this IEnumerable<string>, Func<string, int, TResult>)

...但MYFUNC签名是明确的 - 它只是需要一个(字符串)参数

...but the signature for MyFunc is clear - it just takes one (string) parameter.

任何人都可以提供一些线索吗?

Can anyone shed some light here?

推荐答案

泛型类型推断略有改变 - 在执行方面 - 在C#3和C#编译器4之间。下面是一个简短但完整的示例程序:

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:

using System;
using System.Linq;

class Test
{
    static void Main()
    {
        string[] strings = { "a", "b" };
        var results = strings.Select(MyFunc);
    }

    static bool MyFunc(string input)
    {
        return true;
    }
}

这是编译的C#编译器在.NET 4,但没有一个在.NET 3.5。

That compiles with the C# compiler in .NET 4, but not the one in .NET 3.5.

我的认为的是合理的这个所谓的bug修复,因为我不的认为的,这是一个规范的变化。

I think it's reasonable to call this a bug fix, as I don't think it was a spec change.

如果你必须使用编译器.NET 3.5,你可以添加一个投澄清:

If you have to use the compiler from .NET 3.5, you can add a cast to clarify:

var results = strings.Select((Func<string,bool>) MyFunc);

var results = strings.Select(new Func<string,bool>(MyFunc));

或者你可以把类型参数明确的:

or you could make the type argument explicit:

var results = strings.Select<string, bool>(MyFunc);