Lambda parameter name (sometimes) conflicting with local name

ⅰ亾dé卋堺 提交于 2020-04-03 04:46:31

问题


There are two projects, one is a library targeting .NET Standard 2.0, while the other is a console app targeting .NET Core 2.2.

Now this piece of code is working on .NET Standard 2.0 library, but not on .NET Core 2.2.

for (int i = 0; i < 1; i++) {
    var y = new int[1].First(i => i == 0); // Conflict i name error here in .NET Core 2.2.
    Console.WriteLine("Hello " + y);
}

I understand from this question that simple names should not have different meanings, and thus, even .NET Standard 2.0 library should give an error, but it is not. Why is this inconsistency?

I have tried dotnet fiddle, and it seems to work on .NET Core 3.1 and Roslyn 3.4, but not .NET Framework 4.7.2, which is even more confusing. What is going on here?

  • .Net Core 3.1 (passing) https://dotnetfiddle.net/Cc1hmk

  • Roslyn 3.4 (passing) https://dotnetfiddle.net/megBiw

  • .NET Framework 4.7.2 (Compile error) https://dotnetfiddle.net/6PPqDs


回答1:


What is going on here?

Basically, the ability to use a lambda expression parameter with the same name as an existing local variable is a new feature introduced in the C# 8 compiler - but there's been very little fuss about it. I happened to hear about it (from Mads himself) in a meeting this week, but otherwise wouldn't have known about it.

The target framework matters because it changes the default language version that the compiler applies. You can specify it explicitly using the <LangVersion> element though. For example, with this project file:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net471</TargetFramework>
    <LangVersion>8.0</LangVersion>
  </PropertyGroup>
</Project>

... the code builds fine. Ditto when targeting netstandard2.0 or netcoreapp2.2.



来源:https://stackoverflow.com/questions/60559440/lambda-parameter-name-sometimes-conflicting-with-local-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!