完整的 .NET 框架和 .NET Core 之间的 lambda 表达式差异
Difference in lambda expressions between full .NET framework and .NET Core
.NET Framework 和 .NET Core 的 lambda 表达式声明有区别吗?
以下表达式在 .NET Core 中编译:
var lastShift = timeline.Appointments
.OfType<DriverShiftAppointment>()
.SelectMany(x => x.Activities.Where(x => !x.IsTheoretical))
.OrderByDescending(x => x.Start)
.FirstOrDefault();
但不在 .NET 框架中。
这个表达式中的问题是以下部分
.SelectMany(x => x.Activities.Where(x => !x.IsTheoretical))
其中 x
声明了两次(SelectMany
和 Where
)。
这是 .NET Framework 中的错误:
A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
.NET 框架
可重现的例子:
public class DemoClass
{
public IList<int> Numbers { get; set; } = new List<int>();
}
class Program
{
static void Main(string[] args)
{
var lst = new List<DemoClass>
{
new DemoClass
{
Numbers = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8 }
},
new DemoClass
{
Numbers = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8 }
},
new DemoClass
{
Numbers = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8 }
}
};
var result = lst.SelectMany(x => x.Numbers.Where(x => x % 2 == 0))
.OrderByDescending(x => x);
Console.WriteLine("Hello World!");
}
}
告诉你问题出在这一行:
.SelectMany(x => x.Activities.Where(x => !x.IsTheoretical))
两次使用x会把它搞糊涂,有歧义,试试这个:
.SelectMany(x => x.Activities.Where(y => !y.IsTheoretical))
但你是对的,它编译在核心而不是框架。它看起来像这样:https://github.com/dotnet/roslyn/issues/38377。阅读 link,看起来这是 C# 8.0 中的更改,核心目标是 8.0,而框架目标是 7.2。
.NET Framework 和 .NET Core 的 lambda 表达式声明有区别吗?
以下表达式在 .NET Core 中编译:
var lastShift = timeline.Appointments
.OfType<DriverShiftAppointment>()
.SelectMany(x => x.Activities.Where(x => !x.IsTheoretical))
.OrderByDescending(x => x.Start)
.FirstOrDefault();
但不在 .NET 框架中。
这个表达式中的问题是以下部分
.SelectMany(x => x.Activities.Where(x => !x.IsTheoretical))
其中 x
声明了两次(SelectMany
和 Where
)。
这是 .NET Framework 中的错误:
A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
.NET 框架
可重现的例子:
public class DemoClass
{
public IList<int> Numbers { get; set; } = new List<int>();
}
class Program
{
static void Main(string[] args)
{
var lst = new List<DemoClass>
{
new DemoClass
{
Numbers = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8 }
},
new DemoClass
{
Numbers = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8 }
},
new DemoClass
{
Numbers = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8 }
}
};
var result = lst.SelectMany(x => x.Numbers.Where(x => x % 2 == 0))
.OrderByDescending(x => x);
Console.WriteLine("Hello World!");
}
}
告诉你问题出在这一行:
.SelectMany(x => x.Activities.Where(x => !x.IsTheoretical))
两次使用x会把它搞糊涂,有歧义,试试这个:
.SelectMany(x => x.Activities.Where(y => !y.IsTheoretical))
但你是对的,它编译在核心而不是框架。它看起来像这样:https://github.com/dotnet/roslyn/issues/38377。阅读 link,看起来这是 C# 8.0 中的更改,核心目标是 8.0,而框架目标是 7.2。