繁体   English   中英

完整 .NET 框架和 .NET 核心之间 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被声明了两次( SelectManyWhere )。

这是 .NET 框架中的错误:

不能在此 scope 中声明名为“x”的本地或参数,因为该名称在封闭的本地 scope 中用于定义本地或参数

.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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM