Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 否则速记赢了';没有任务就不能工作_C#_If Statement - Fatal编程技术网

C# 否则速记赢了';没有任务就不能工作

C# 否则速记赢了';没有任务就不能工作,c#,if-statement,C#,If Statement,在C#中,我试图缩短一些返回代码。我想做的是 condition ? return here:return there; 或 但是我有一些问题,编译器说表达式无效。以下是一个例子: int i = 1; int a = 2; i < a ? i++ : a++; 我真的希望这行代码看起来更像: boolCondition ? return toThisPlace():; 这是无效的,但正是我想要的。您需要将返回移动到三元操作之外 ret

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

condition ? return here:return there;

但是我有一些问题,编译器说表达式无效。以下是一个例子:

        int i = 1;
        int a = 2;
        i < a ? i++ : a++;
我真的希望这行代码看起来更像:

boolCondition ? return toThisPlace():;

这是无效的,但正是我想要的。

您需要将返回移动到三元操作之外

return boolCondition ? toThisPlace() : 0 ; 

你的陈述有问题

而不是

condition ? return here:return there;
正如您所发现的,它不会编译,而是

return condition ? here: there;

你需要这样写你的陈述

return condition ? here : there;
?:不是if/else的“速记”-它是具有特定语义规则的特定运算符(条件)。这些规则意味着它只能用作表达式,不能用作语句

关于返回:如果您只想“如果为true,则返回”,则将其编码为:

if(condition) return [result];

不要试图使用条件运算符作为非条件运算符。

不,这是不可能的
return
是一条语句;它不能是表达式的一部分,这是三元运算符(不是逻辑控制语句)在其所有三个操作数中所期望的。你必须用通常的形式。不过,别担心,这是一件好事——从长远来看,它会使代码更具可读性。

三元运算符
?:
在C中受到限制。在这种情况下,您可以做的是:

return condition ? here : there;

您的代码正常唯一的问题是您在条件下读取i变量,同时尝试更改变量的值。答案如下(取决于您的C版本和需要):

现在,您可以将结果指定给将被忽略的下划线“\u1”变量:

_ = i < a ? i++ : a++;

如果我这样做,如果条件为false,它不会返回0吗?我只想在为true时返回。在这种情况下,您必须使用
if
<代码>如果(布尔条件)返回到此位置()。三元运算符不能代替if-else;聪明的代码就是坏代码。你在这里不是在写侦探小说或逻辑谜题书;当代码正确且易于理解时,它是有价值的。更具体地说:使用表达式进行计算,使用语句进行控制流。您试图使用控制流表达式,这与工具的设计背道而驰,而不是使用它。@EricLippert-我正在编写一本完全用c#编写的动作/冒险小说,其前提是所有代码都要聪明。第1页:
IScene OpeningScene=new PanoramicScene();OpeningScene.panToAction()它将被称为“黑暗中的I c”,以狼人为特色。但是回到正题,谢谢你的提示。我会记住这一点。
if(condition) return [result];
return condition ? here : there;
return condition ? here : there;
return here ?? there; // if you want there when here is null

return boolCondition ? toThisPlace() : default;
return boolCondition ? toThisPlace() : default(int);
return boolCondition ? toThisPlace() : 0;
_ = i < a ? i++ : a++;
if (i < a)
{
    i++;
}
else
{
    a++;
}
_ = boolCondition = return toThisPlace() : default; // this is horrible, don't do it