使用三元运算符进行多项操作 [英] Using the ternary operator for multiple operations
问题描述
如果expression为true/false,如何使用三元? :
条件执行多项操作?
How can I use the ternary ? :
condition to perform multiple operations, if expression is true/false?
wbsource = (exp) ? (Do one 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条件,我将以一种简单的方式编写:
With simple if condition, I would have written in a simple way like:
if(fp!null)
{
filename = fp;
Properties.Settings.Default.filename;
Properties.Settings.Default.Save();
}
else
{
filename = Properties.Settings.Default.file
}
使用上述三元运算符写代码的最佳方法是什么?
What's a sweet short way to write using the above ternary operator?
推荐答案
为什么我之间不能执行三个操作?和:
Why can't I perform three operations between ? and :
因为这些是操作数,它们是表达式.每个表达式评估一个值;您需要多个声明.摘自Eric Lippert的关于foreach
的博客文章与ForEach
:
Because these are operands, which are expressions. Each expression evaluates a value; you want multiple statements. From Eric Lippert's blog post about foreach
vs ForEach
:
第一个原因是这样做违反了所有其他序列运算符所基于的功能编程原理.显然,调用此方法的唯一目的是引起副作用.
The first reason is that doing so violates the functional programming principles that all the other sequence operators are based upon. Clearly the sole purpose of a call to this method is to cause side effects.
表达式的目的是计算值,而不引起副作用.声明的目的是引起副作用.这个东西的调用位置看起来很像一个表达式(尽管,诚然,由于该方法是空返回的,所以该表达式只能在语句表达式"上下文中使用.)
The purpose of an expression is to compute a value, not to cause a side effect. The purpose of a statement is to cause a side effect. The call site of this thing would look an awful lot like an expression (though, admittedly, since the method is void-returning, the expression could only be used in a "statement expression" context.)
您绝对应该使用if
块来编写此代码.更清楚了.
You should absolutely write this using an if
block. It's clearer.
如果您真的真的想使用条件运算符,可以这样写:
If you really, really want to use the conditional operator for this, you could write:
// Please, please don't use this.
Func<string> x = () => {
Properties.Settings.Default.filename = fp;
Properties.Settings.Default.Save();
return fp;
};
string filename = fp == null ? Properties.Settings.Default.file : x();
这篇关于使用三元运算符进行多项操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!