c# - 为什么这段代码不能在 .NET 4.0 的 VS2010 中编译?

标签 c# .net visual-studio-2010 linq visual-studio-2012

不知何故,以下代码无法在 VS2010 中编译,但可以在 VS2012 中编译而无需更改。 VS2010 中有问题的行是

names.Select(foo.GetName)

error CS1928: 'string[]' does not contain a definition for 'Select' and the best extension method overload 'System.Linq.Enumerable.Select<TSource,TResult>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TResult>)' has some invalid arguments.

using System;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            var foo = new Foo();
            var names = new[] {"Hello"};
            Console.WriteLine(string.Join(", ", names.Select(foo.GetName)));
        }
    }

    public class Foo
    {
    }

    static class Extensions
    {
        public static string GetName(this Foo foo, string name)
        {
            return name;
        }
    }
}

最佳答案

更新的答案

我已经检查过代码片段 names.Select(foo.GetName)在 VS 2012 中编译,在 VS2010 中不编译。

我不知道使它成为可能的原因(确切地说是 C# 5.0 或 .NET 4.5 或新 API 中的新功能)。

但是下面报错

The type arguments for method 'System.Linq.Enumerable.Select<TSource,TResult>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource,TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

好像Enumerable.Select无法推断 foo.GetName 的参数和返回类型.

指定类型,代码将编译。

以下是3个选项

1 。转换为 Func<string,string>

string.Join(", ", names.Select<string,string>(foo.GetName).ToArray())

2。在 Select 中将类型指定为通用参数子句

string.Join(", ", names.Select((Func<string,string>)foo.GetName).ToArray())

3。在匿名委托(delegate)中显式调用函数。

 Console.WriteLine(string.Join(", ", names.Select( name => foo.GetName(name))))

但正如 Jon Skeet 在评论中指出的那样,上面将通过创建新方法来添加另一个函数调用。

原始答案

why this code doesn't compile in VS2010 with .NET 4.0?

您没有将参数传递给名称。您正在传递方法名称,代替 Func<T1,T2> .


下面会编译

Console.WriteLine(string.Join(", ", names.Select( name => foo.GetName(name))))

关于c# - 为什么这段代码不能在 .NET 4.0 的 VS2010 中编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14320510/

相关文章:

asp.net-mvc - ASP.NET MVC3 在 Windows 8 中不工作

c# - 在哪里可以了解有关 P/Invoke 的更多信息?

c# - 接受所有已注册类型/实例列表的 Structuremap 3 构造函数

c# - 通过 slug 获取内容项的正确方法

.net - 从您的方法返回异常是不好的做法

c++ - 是否需要 std::unique_ptr<T> 才能知道 T 的完整定义?

c++ - 在 Visual Studio 中自动化 DLL 调试 "attach to process"?

C# 仅在需要时有条件地处置 Entity Framework DbContext

c# - 注册 dll - 在注册表中找不到 GUID

c# - 比较两个 int 数组