完整.NET框架和.NETCore之间lambda表达式的差异

c#

.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))
.SelectMany(x => x.Activities.Where(x => !x.IsTheoretical))

wherex声明了两次(SelectManyWhere)。

这是 .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!");
    }
}

回答

它告诉你问题是这一行:

使用 x 两次会混淆它,这是模棱两可的,试试这个:

.SelectMany(x => x.Activities.Where(y => !y.IsTheoretical))

但是你是对的,它在核心而不是框架中编译。它看起来像这样:https : //github.com/dotnet/roslyn/issues/38377。阅读该链接,看起来这是 C# 8.0 中的更改,核心针对 8.0,而框架针对 7.2。

  • Nice find on the issue. It would be good if you could update your answer to say that this is a change introduced in C# 8, and not a .NET Core / .NET Framework difference
  • Probably differences in C# compiler. Anyway try to avoid this.

以上是完整.NET框架和.NETCore之间lambda表达式的差异的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>