gpt4 book ai didi

c# - 如果没有赋值,If Then Else 速记将不起作用

转载 作者:行者123 更新时间:2023-11-30 13:09:28 25 4
gpt4 key购买 nike

在 C# 中,我试图缩短一些返回代码。我想做的是类似

condition ? return here:return there;

condition ?? return here;

不过我遇到了一些问题,编译器说表达式无效。这是一个例子:

        int i = 1;
int a = 2;
i < a ? i++ : a++;

这是无效的。然而,

        int i = 1;
int a = 2;
int s = i < a ? i++ : a++;

有效。必须要有赋值才能使用这个速记符号吗?目前我能想到的唯一使用方法是:

int acceptReturn = boolCondition ? return toThisPlace() : 0 ;

我真的希望那行代码看起来更像:

boolCondition ? return toThisPlace():;

这是无效的,但正是我所追求的。

最佳答案

? : 不是 if/else 的“简写”——它是具有特定语义规则的特定运算符(条件)。这些规则意味着它只能用作表达式,不能用作语句。

关于返回:如果你只想“如果为真则返回”,那么就这样编码:

if(condition) return [result];

不要尝试使用条件运算符。

关于c# - 如果没有赋值,If Then Else 速记将不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9370340/

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