gpt4 book ai didi

c# - 为什么我不能在带有丢弃参数的 lambda 中使用丢弃参数?

转载 作者:行者123 更新时间:2023-11-30 20:16:41 25 4
gpt4 key购买 nike

我正在使用新的 .NET 工具编写 C# 库。我正在尝试使用 discards来自 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);
});
});
}
}

建筑:

% 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

最佳答案

您正在尝试使用丢弃物,但您的方案没有。 _ 参数只是常规变量。如果您更改代码以从 _ 参数添加赋值,您会看到这一点:

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

g("y", (i, _) => {
Console.WriteLine(i);
});
});
}

如果外层 lambda 中的 _ 实际上是丢弃的,就会出现编译器错误。但是没有。它只是一个普通的旧变量,你会得到一个普通的旧“that name is used”错误。

关于c# - 为什么我不能在带有丢弃参数的 lambda 中使用丢弃参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48072785/

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