使用三元运算符进行多个运算

我该如何使用三元? : ? :如果表达式为true / false,则执行多个操作的条件?

wbsource = (exp) ? (Do one thing) : (Do second thing) wbsource = (exp) ? (Do one thing) : (Do second thing) wbsource = (exp) ? (Do one thing) (Do second thing) : (Do second thing) wbsource = (exp) ? (Do one thing) (Do second thing) : (Do second thing)

例如:

为什么我不能在两者之间执行三次操作? 并且:

 filename = (fp!=null) ? fp; Properties.Settings.Default.filename=fp; Properties.Settings.Default.Save; : Properties.Settings.Default.file; 

有了简单的if条件,我会用简单的方式写:

 if(fp!null) { filename = fp; Properties.Settings.Default.filename; Properties.Settings.Default.Save(); } else { filename = Properties.Settings.Default.file } 

使用上述三元运算符编写的简短方法是什么?

为什么我不能在两者之间执行三次操作? 并且:

因为这些是操作数 ,它们是表达式 。 每个表达式都会计算一个值; 你想要多个陈述 。 来自Eric Lippert 关于foreach vs ForEach的博文 :

第一个原因是这样做违反了所有其他序列运算符所基于的函数式编程原则。 显然,调用此方法的唯一目的是引起副作用。

表达式的目的是计算一个值,而不是产生副作用。 声明的目的是产生副作用。 这个东西的调用站点看起来很像表达式(但是,诚然,因为该方法是void返回的,所以表达式只能用在“语句表达式”上下文中。)

你绝对应该用if块写这个。 它更清楚。

如果你真的,真的想使用条件运算符,你可以写:

 // Please, please don't use this. Func x = () => { Properties.Settings.Default.filename = fp; Properties.Settings.Default.Save(); return fp; }; string filename = fp == null ? Properties.Settings.Default.file : x(); 

条件运算符是三元运算符(不是一元运算符),不是if语句的替代。 它是一个返回两个结果之一的运算符。 虽然你可以在某种程度上链接这个:

 var result = someBool ? "a" : (otherBool ? "b" : "c"); 

这有点难以阅读。 此外,您正在尝试调用Save()函数,该函数不返回结果,因此您无法将其与此运算符一起使用。

如果你真的,真的想,你可以使用一个有副作用的function:

 filename = (fp!=null) ? DoOneThing(...) : DoAnotherThing(...); 

虽然维护代码的人不会感谢你。

如果这是c那么感谢“逗号运算符” :

 int b; int a = (1==1) ? (b=6, somemethod(), 1) : (b=7, 2); 

这里b将被设置为6,将调用somemethod然后将a设置为1。

值得庆幸的是,这是一个没有移植的function,使用if..else它更清晰。

简短的回答,使用if块,这是唯一理智的事情。

其他答案,对于肮脏,有臭味的疯狂个体。

 filename = (fp!=null) ? Func {fp = Properties.Settings.Default.filename; Properties.Settings.Default.Save; return fp;} : Properties.Settings.Default.file;