简单的LINQ EX pression不会编译 [英] Simple Linq expression won't compile

查看:87
本文介绍了简单的LINQ EX pression不会编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有了这些基本的定义

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

这篇关于简单的LINQ EX pression不会编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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