不知何故,以下代码无法在 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/