c# - 完整的 .NET 框架和 .NET Core 之间 lambda 表达式的差异
问题描述
.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))
wherex
被声明了两次(SelectMany
和Where
)。
这是 .NET Framework 中的错误:
不能在此范围内声明名为“x”的本地或参数,因为该名称在封闭的本地范围中用于定义本地或参数
.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 。阅读该链接,看起来这是 C# 8.0 中的一个变化,核心面向 8.0,而框架面向 7.2。