gpt4 book ai didi

c# - 不允许在 C# 的语句中使用短路函数调用?

转载 作者:太空宇宙 更新时间:2023-11-03 23:20:08 25 4
gpt4 key购买 nike

我试图在两个函数调用之间使用短路。以这段代码为例:

private void BubbleDown(Graph.Vertex item)
{
BubbleDownLeft(item) || BubbleDownRight(item);
}

BubbleDownLeftBubbleDownRight 都返回 bool 值。这会引发以下错误:

Error CS0201 - Only assignment, call, increment, decrement, and new object expressions can be used as a statement

我知道我可以很容易地重写函数以使用 if 语句(但这不是那么漂亮)或者甚至只是将它分配给一个我不使用的值:

private void BubbleDown(Graph.Vertex item)
{
bool ignoreMe = BubbleDownLeft(item) || BubbleDownRight(item);
}

那么为什么我的第一个编码示例是一个错误而不是有效的或者可能只是一个警告?

最佳答案

建议的代码对计算机没有意义。当您要求它 BubbleDown() 时,您告诉它要么 BubbleDownLeft() 要么 BubbleDownRight() 但也忽略结果。编译器没有动机使用 short-circuit evaluation因为无论如何结果都会被忽略。此短路评估是 if 的启动,这是一个 if 语句。

在您的评论中声明:

I'll agree the extraneous ignoreMe is worse than an if, but the original is easily read. It clearly says that bubbleDown is the result of either the left or the right. Going with the a, b, c, d, e, example, you would have to put if (!(a() || b() || c() || d())) e()) which would look like e() is the goal, but really it's a 5-branching path where the first path to succeed is taken.

这清楚地表明您想要进行短路评估,您可以选择更改返回类型并执行以下操作:

private bool BubbleDown(Graph.Vertex item)
{
return BubbleDownLeft(item) || BubbleDownRight(item);
}

或者您可以选择带有空 block 的 if 语句。注意 ;if 语句之后:

private void BubbleDown(Graph.Vertex item)
{
if (BubbleDownLeft(item) || BubbleDownRight(item)) ;
}

我想我更喜欢第一个,然后在您调用 BubbleDown() 时简单地忽略返回值,或者实际验证它确实如实执行了任何选项。

关于c# - 不允许在 C# 的语句中使用短路函数调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35710699/

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