gpt4 book ai didi

c# - 完整.NET Framework和.NET Core之间的lambda表达式差异

转载 作者:行者123 更新时间:2023-12-03 15:46:19 25 4
gpt4 key购买 nike

.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 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框架
enter image description here
可重现的示例:
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。

关于c# - 完整.NET Framework和.NET Core之间的lambda表达式差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66778226/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com