为什么我不能在具有discard参数的lambda中使用discard参数?

Eth*_*sor 2 .net c#

我正在使用新的.NET工具编写C#库.我正在尝试使用C#7.0中的丢弃程序.我遇到了编译器将其_视为参数而不是丢弃的问题.

例:

using System;

public delegate void Delegate1(string a, Delegate2 b);
public delegate void Delegate2(int a, Delegate3 b);
public delegate void Delegate3(string a, Delegate4 b);
public delegate void Delegate4(int a, int b);

class Program
{
    void Test(Delegate1 f)
    {
        f("x", (_, g) => {
            g("y", (i, _) => {
                Console.WriteLine(i);
            });
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

建造:

% dotnet build                                                                                                                                                                                                                                                       ~/Source/temp
Microsoft (R) Build Engine version 15.5.179.9764 for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

Restore completed in 18.6 ms for /Users/me/Source/temp/temp.csproj.
Program.cs(13,24): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter [/Users/me/Source/temp/temp.csproj]

Build FAILED.

Program.cs(13,24): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter [/Users/me/Source/temp/temp.csproj]
    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:02.45
Run Code Online (Sandbox Code Playgroud)

Pet*_*iho 6

您正在尝试使用丢弃程序,但您的方案没有.该_参数是只是普通的变量.如果更改代码以从_参数添加分配,则可以看到此内容:

void Test(Delegate1 f)
{
    f("x", (_, g) => {
        int a = _;

        g("y", (i, _) => {
            Console.WriteLine(i);
        });
    });
}
Run Code Online (Sandbox Code Playgroud)

如果_外部lambda实际上是丢弃的,那么就会出现编译器错误.但事实并非如此.它只是一个普通的旧变量,你会得到一个简单的"使用该名称"错误.