簡體   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