What are the benefits and drawbacks of the ?: operator as opposed to the standard if-else statement. The obvious ones being:
与标准的if-else语句相比,?:操作符的优点和缺点是什么。最明显的是:
Conditional ?: Operator
条件:操作符
- Shorter and more concise when dealing with direct value comparisons and assignments
- 在处理直接价值比较和赋值时更简短
- Doesn't seem to be as flexible as the if/else construct
- 似乎不像if/else结构那样灵活
Standard If/Else
标准如果/其他
- Can be applied to more situations (such as function calls)
- 可以应用于更多的情况(例如函数调用)
- Often are unnecessarily long
- 常常不必要的长
Readability seems to vary for each depending on the statement. For a little while after first being exposed to the ?: operator, it took me some time to digest exactly how it worked. Would you recommend using it wherever possible, or sticking to if/else given that I work with many non-programmers?
可读性似乎因语句的不同而不同。在第一次接触到操作符之后的一段时间里,我花了一些时间来消化它是如何工作的。你会建议尽可能地使用它,还是坚持使用if/else,因为我和很多非程序员一起工作?
17 个解决方案
#1
113
I would basically recommend using it only when the resulting statement is extremely short and represents a significant increase in conciseness over the if/else equivalent without sacrificing readability.
我基本上只建议在得到的语句非常短并且在不牺牲可读性的前提下显著提高if/else的简洁性时使用它。
Good example:
很好的例子:
int result = Check() ? 1 : 0;
Bad example:
不好的例子:
int result = FirstCheck() ? 1 : SecondCheck() ? 1 : ThirdCheck() ? 1 : 0;
#2
47
This is pretty much covered by the other answers, but "it's an expression" doesn't really explain why that is so useful...
其他的答案几乎都涵盖了这一点,但是“it’s a expression”并不能真正解释为什么它这么有用……
In languages like C++ and C#, you can define local readonly fields (within a method body) using them. This is not possible with a conventional if/then statement because the value of a readonly field has to be assigned within that single statement:
在c++和c#这样的语言中,您可以使用它们定义本地只读字段(在方法主体内)。这对于传统的if/then语句是不可能的,因为readonly字段的值必须在该语句中分配:
readonly int speed = (shiftKeyDown) ? 10 : 1;
is not the same as:
是不一样的:
readonly int speed;
if (shifKeyDown)
speed = 10; // error - can't assign to a readonly
else
speed = 1; // error
In a similar way you can embed a tertiary expression in other code. As well as making the source code more compact (and in some cases more readable as a result) it can also make the generated machine code more compact and efficient:
类似地,可以在其他代码中嵌入第三个表达式。除了使源代码更紧凑(在某些情况下更易于阅读),它还可以使生成的机器代码更紧凑和高效:
MoveCar((shiftKeyDown) ? 10 : 1);
...may generate less code than having to call the same method twice:
…可能生成的代码比必须调用同一方法两次要少:
if (shiftKeyDown)
MoveCar(10);
else
MoveCar(1);
Of course, it's also a more convenient and concise form (less typing, less repetition, and can reduce the chance of errors if you have to duplicate chunks of code in an if/else). In clean "common pattern" cases like this:
当然,它也是一种更方便、更简洁的表单(更少的输入,更少的重复,如果你需要在if/else中复制代码块,可以减少出错的几率)。在清洁的“常见模式”案例中:
object thing = (reference == null) ? null : reference.Thing;
... it is simply faster to read/parse/understand (once you're used to it) than the long-winded if/else equivalent, so it can help you to 'grok' code faster.
…读/解析/理解(一旦您习惯了)比冗长的if/else等价物更快,因此它可以帮助您更快地“摸索”代码。
Of course, just because it is useful does not mean it is the best thing to use in every case. I'd advise only using it for short bits of code where the meaning is clear (or made more clear) by using ?:
- if you use it in more complex code, or nest ternary operators within each other it can make code horribly difficult to read.
当然,仅仅因为它有用并不意味着它在任何情况下都是最好的。我建议只对那些意义明确(或更清楚)的简短代码使用?::——如果您在更复杂的代码中使用它,或者在彼此之间使用嵌套三元运算符,则会使代码难以阅读。
#3
10
I find it particularly helpful when doing web development if I want to set a variable to a value sent in the request if it is defined or to some default value if it is not.
在进行web开发时,如果我想要将变量设置为请求中发送的值(如果定义了该值),或者设置为未定义的某个默认值(如果没有),我发现这一点特别有用。
#4
10
I usually choose a ternary operator when I'd have a lot of duplicate code otherwise.
如果我有很多重复的代码,我通常会选择三元运算符。
if (a > 0)
answer = compute(a, b, c, d, e);
else
answer = compute(-a, b, c, d, e);
With a ternary operator, this could be accomplished with the following.
使用三元运算符,可以通过以下操作来完成。
answer = compute(a > 0 ? a : -a, b, c, d, e);
#5
10
A really cool usage is:
一个非常酷的用法是:
x = foo ? 1 :
bar ? 2 :
baz ? 3 :
4;
#6
5
The conditional operator is great for short conditions, like this:
条件算子对于短条件是很好的,比如:
varA = boolB ? valC : valD;
I use it occasionally because it takes less time to write something that way... unfortunately, this branching can sometimes be missed by another developer browsing over your code. Plus, code isn't usually that short, so I usually help readability by putting the ? and : on separate lines, like this:
我偶尔使用它,因为这样写东西花费的时间更少……不幸的是,这种分支有时会被浏览代码的其他开发人员忽略。另外,代码通常不是那么短,所以我通常通过放置?在不同的行上,像这样:
doSomeStuffToSomething(shouldSomethingBeDone()
? getTheThingThatNeedsStuffDone()
: getTheOtherThingThatNeedsStuffDone());
However, the big advantage to using if/else blocks (and why I prefer them) is that it's easier to come in later and add some additional logic to the branch,
然而,使用if/else块(以及我为什么喜欢它们)的最大好处是,以后更容易进入并向分支添加一些额外的逻辑,
if (shouldSomethingBeDone()) {
doSomeStuffToSomething(getTheThingThatNeedsStuffDone());
doSomeAdditionalStuff();
} else {
doSomeStuffToSomething(getTheOtherThingThatNeedsStuffDone());
}
or add another condition:
或添加另一个条件:
if (shouldSomethingBeDone()) {
doSomeStuffToSomething(getTheThingThatNeedsStuffDone());
doSomeAdditionalStuff();
} else if (shouldThisOtherThingBeDone()){
doSomeStuffToSomething(getTheOtherThingThatNeedsStuffDone());
}
So, in the end, it's about convenience for you now (shorter to use :?) vs. convenience for you (and others) later. It's a judgment call... but like all other code-formatting issues, the only real rule is to be consistent, and be visually courteous to those who have to maintain (or grade!) your code.
所以,最终,它是关于方便你现在(更短的使用:?)和方便你(和其他人)以后。这是一个主观判断的问题……但是,与所有其他代码格式问题一样,唯一真正的规则是保持一致,并在视觉上礼貌地对待那些必须维护(或升级)您的代码的人。
(all code eye-compiled)
(所有代码eye-compiled)
#7
4
One thing to recognize when using the ternary operator that it is an expression not a statement.
当使用三元运算符时,需要注意的一点是它是一个表达式而不是一个语句。
In functional languages like scheme the distinction doesn't exists:
在像scheme这样的函数式语言中,这种区别并不存在:
(if (> a b) a b)
(如果(> a b) a b)
Conditional ?: Operator "Doesn't seem to be as flexible as the if/else construct"
条件?:运算符“似乎不像if/else构造那样灵活”
In functional languages it is.
在函数式语言中是这样的。
When programming in imperative languages I apply the ternary operator in situations where I typically would use expressions (assignment, conditional statements, etc).
当用命令式语言编程时,我在通常使用表达式(赋值、条件语句等)的情况下应用三元运算符。
#8
4
While the above answers are valid, and I agree with readability being important, there are 2 further points to consider:
虽然上述答案是有效的,我同意可读性是重要的,但还有两点需要考虑:
- In C#6, you can have expression-bodied methods.
- 在c# 6中,你可以有表达体方法。
This makes it particularly concise to use the ternary:
这使得使用ternary特别简洁:
string GetDrink(DayOfWeek day)
=> day == DayOfWeek.Friday
? "Beer" : "Tea";
- Behaviour differs when it comes to implicit type conversion.
- 当涉及到隐式类型转换时,行为会有所不同。
If you have types T1
and T2
that can both be implicitly converted to T
, then the below does not work:
如果有可以隐式转换为T的类型T1和T2,那么下面的就不起作用了:
T GetT() => true ? new T1() : new T2();
(because the compiler tries to determine the type of the ternary expression, and there is no conversion between T1
and T2
.)
(因为编译器试图确定三元表达式的类型,并且在T1和T2之间没有转换。)
On the other hand, the if/else
version below does work:
另一方面,下面的if/else版本确实有效:
T GetT()
{
if (true) return new T1();
return new T2();
}
because T1
is converted to T
and so is T2
因为T1转化为T, T2也是
#9
4
Sometimes it can make the assignment of a bool value easier to read at first glance:
有时它可以使bool值的赋值第一眼看上去更容易阅读:
// With
button.IsEnabled = someControl.HasError ? false : true;
// Without
button.IsEnabled = !someControl.HasError;
#10
3
If I'm setting a value and I know it will always be one line of code to do so, I typically use the ternary (conditional) operator. If there's a chance my code and logic will change in the future, I use an if/else as it's more clear to other programmers.
如果我正在设置一个值,并且我知道这将始终是一行代码,我通常使用三元(条件)运算符。如果我的代码和逻辑有可能在未来发生变化,我就使用If /else,因为其他程序员更清楚这一点。
Of further interest to you may be the ?? operator.
对你更感兴趣的可能是?操作符。
#11
3
The advantage of the conditional operator is that it is an operator. In other words, it returns a value. Since if
is a statement, it cannot return a value.
条件运算符的优点是它是一个运算符。换句话说,它返回一个值。因为if是一个语句,所以它不能返回一个值。
#12
3
I'd recommend limiting the use of the ternary(?:) operator to simple single line assignment if/else logic. Something resembling this pattern:
我建议将三元(?)运算符的使用限制为简单的单行赋值if/else逻辑。类似这种模式:
if(<boolCondition>) {
<variable> = <value>;
}
else {
<variable> = <anotherValue>;
}
Could be easily converted to:
可以很容易地转换为:
<variable> = <boolCondition> ? <value> : <anotherValue>;
I would avoid using the ternary operator in situations that require if/else if/else, nested if/else, or if/else branch logic that results in the evaluation of multiple lines. Applying the ternary operator in these situations would likely result in unreadable, confusing, and unmanageable code. Hope this helps.
我将避免在需要if/else if/else、嵌套if/else或if/else分支逻辑的情况下使用三元运算符。在这些情况下应用三元运算符可能会导致不可读、混乱和难以管理的代码。希望这个有帮助。
#13
1
There is some performance benefit of using the the ? operator in eg. MS Visual C++, but this is a really a compiler specific thing. The compiler can actually optimize out the conditional branch in some cases.
使用?运营商。MS Visual c++,但这确实是一个特定于编译器的东西。在某些情况下,编译器可以优化条件分支。
#14
1
The scenario I most find myself using it is for defaulting values and especially in returns
我最常使用的场景是针对默认值,尤其是在回报方面
return someIndex < maxIndex ? someIndex : maxIndex;
Those are really the only places I find it nice, but for them I do.
那些是我觉得不错的地方,但对他们来说我是。
Though if you're looking for a boolean this might sometimes look like an appropriate thing to do:
虽然如果你在寻找一个布尔值,这有时看起来是一个合适的做法:
bool hey = whatever < whatever_else ? true : false;
Because it's so easy to read and understand, but that idea should always be tossed for the more obvious:
因为它很容易阅读和理解,但这个想法应该被抛到更明显的位置:
bool hey = (whatever < whatever_else);
#15
1
If you need multiple branches on the same condition, use an if:
如果在同一条件下需要多个分支,请使用If:
if (A == 6)
f(1, 2, 3);
else
f(4, 5, 6);
If you need multiple branches with different conditions, then if statement count would snowball, you'll want to use the ternary:
如果您需要多个具有不同条件的分支,那么如果语句计数会滚雪球式地增加,您将需要使用三元:
f( (A == 6)? 1: 4, (B == 6)? 2: 5, (C == 6)? 3: 6 );
Also, you can use the ternary operator in initialization.
此外,您可以在初始化中使用三元运算符。
const int i = (A == 6)? 1 : 4;
Doing that with if is very messy:
用if来做这件事很麻烦:
int i_temp;
if (A == 6)
i_temp = 1;
else
i_temp = 4;
const int i = i_temp;
You can't put the initialization inside the if/else, because it changes the scope. But references and const variables can only be bound at initialization.
不能将初始化放在if/else中,因为它改变了范围。但是引用和const变量只能在初始化时绑定。
#16
1
The ternary operator can be included within an rvalue, whereas an if-then-else cannot; on the other hand, an if-then-else can execute loops and other statements, whereas the ternary operator can only execute (possibly void) rvalues.
三元运算符可以包含在rvalue中,而if-then-else不能;另一方面,if-then-else可以执行循环和其他语句,而三元运算符只能执行(可能无效)的值。
On a related note, the && and || operators allow some execution patterns which are harder to implement with if-then-else. For example, if one has several functions to call and wishes to execute a piece of code if any of them fail, it can be done nicely using the && operator. Doing it without that operator will either require redundant code, a goto, or an extra flag variable.
与此相关的是,&&和||操作符允许使用if-then-else实现某些执行模式,而这些执行模式很难实现。例如,如果有几个函数要调用并希望在其中任何一个失败时执行一段代码,可以使用&& &操作符很好地完成。在没有操作符的情况下进行操作,将需要冗余代码、goto或额外的标志变量。
#17
0
With C# 7, you can use the new ref locals feature to simplify the conditional assignment of ref-compatible variables. So now, not only can you do:
使用c# 7,您可以使用新的ref局部特性来简化与ref兼容的变量的条件分配。所以现在,你不仅可以做到:
int i = 0;
T b = default(T), c = default(T);
// initialization of C#7 'ref-local' variable using a conditional r-value⁽¹⁾
ref T a = ref (i == 0 ? ref b : ref c);
...but also the extremely wonderful:
…但也非常精彩:
// assignment of l-value⁽²⁾ conditioned by C#7 'ref-locals'
(i == 0 ? ref b : ref c) = a;
That line of code assigns the value of a
to either b
or c
, depending on the value of i
.
这行代码将a的值赋给b或c,这取决于i的值。
Notes
1. r-value is the right-hand side of an assignment, the value that gets assigned.
2. l-value is the left-hand side of an assignment, the variable that receives the assigned value.
#1
113
I would basically recommend using it only when the resulting statement is extremely short and represents a significant increase in conciseness over the if/else equivalent without sacrificing readability.
我基本上只建议在得到的语句非常短并且在不牺牲可读性的前提下显著提高if/else的简洁性时使用它。
Good example:
很好的例子:
int result = Check() ? 1 : 0;
Bad example:
不好的例子:
int result = FirstCheck() ? 1 : SecondCheck() ? 1 : ThirdCheck() ? 1 : 0;
#2
47
This is pretty much covered by the other answers, but "it's an expression" doesn't really explain why that is so useful...
其他的答案几乎都涵盖了这一点,但是“it’s a expression”并不能真正解释为什么它这么有用……
In languages like C++ and C#, you can define local readonly fields (within a method body) using them. This is not possible with a conventional if/then statement because the value of a readonly field has to be assigned within that single statement:
在c++和c#这样的语言中,您可以使用它们定义本地只读字段(在方法主体内)。这对于传统的if/then语句是不可能的,因为readonly字段的值必须在该语句中分配:
readonly int speed = (shiftKeyDown) ? 10 : 1;
is not the same as:
是不一样的:
readonly int speed;
if (shifKeyDown)
speed = 10; // error - can't assign to a readonly
else
speed = 1; // error
In a similar way you can embed a tertiary expression in other code. As well as making the source code more compact (and in some cases more readable as a result) it can also make the generated machine code more compact and efficient:
类似地,可以在其他代码中嵌入第三个表达式。除了使源代码更紧凑(在某些情况下更易于阅读),它还可以使生成的机器代码更紧凑和高效:
MoveCar((shiftKeyDown) ? 10 : 1);
...may generate less code than having to call the same method twice:
…可能生成的代码比必须调用同一方法两次要少:
if (shiftKeyDown)
MoveCar(10);
else
MoveCar(1);
Of course, it's also a more convenient and concise form (less typing, less repetition, and can reduce the chance of errors if you have to duplicate chunks of code in an if/else). In clean "common pattern" cases like this:
当然,它也是一种更方便、更简洁的表单(更少的输入,更少的重复,如果你需要在if/else中复制代码块,可以减少出错的几率)。在清洁的“常见模式”案例中:
object thing = (reference == null) ? null : reference.Thing;
... it is simply faster to read/parse/understand (once you're used to it) than the long-winded if/else equivalent, so it can help you to 'grok' code faster.
…读/解析/理解(一旦您习惯了)比冗长的if/else等价物更快,因此它可以帮助您更快地“摸索”代码。
Of course, just because it is useful does not mean it is the best thing to use in every case. I'd advise only using it for short bits of code where the meaning is clear (or made more clear) by using ?:
- if you use it in more complex code, or nest ternary operators within each other it can make code horribly difficult to read.
当然,仅仅因为它有用并不意味着它在任何情况下都是最好的。我建议只对那些意义明确(或更清楚)的简短代码使用?::——如果您在更复杂的代码中使用它,或者在彼此之间使用嵌套三元运算符,则会使代码难以阅读。
#3
10
I find it particularly helpful when doing web development if I want to set a variable to a value sent in the request if it is defined or to some default value if it is not.
在进行web开发时,如果我想要将变量设置为请求中发送的值(如果定义了该值),或者设置为未定义的某个默认值(如果没有),我发现这一点特别有用。
#4
10
I usually choose a ternary operator when I'd have a lot of duplicate code otherwise.
如果我有很多重复的代码,我通常会选择三元运算符。
if (a > 0)
answer = compute(a, b, c, d, e);
else
answer = compute(-a, b, c, d, e);
With a ternary operator, this could be accomplished with the following.
使用三元运算符,可以通过以下操作来完成。
answer = compute(a > 0 ? a : -a, b, c, d, e);
#5
10
A really cool usage is:
一个非常酷的用法是:
x = foo ? 1 :
bar ? 2 :
baz ? 3 :
4;
#6
5
The conditional operator is great for short conditions, like this:
条件算子对于短条件是很好的,比如:
varA = boolB ? valC : valD;
I use it occasionally because it takes less time to write something that way... unfortunately, this branching can sometimes be missed by another developer browsing over your code. Plus, code isn't usually that short, so I usually help readability by putting the ? and : on separate lines, like this:
我偶尔使用它,因为这样写东西花费的时间更少……不幸的是,这种分支有时会被浏览代码的其他开发人员忽略。另外,代码通常不是那么短,所以我通常通过放置?在不同的行上,像这样:
doSomeStuffToSomething(shouldSomethingBeDone()
? getTheThingThatNeedsStuffDone()
: getTheOtherThingThatNeedsStuffDone());
However, the big advantage to using if/else blocks (and why I prefer them) is that it's easier to come in later and add some additional logic to the branch,
然而,使用if/else块(以及我为什么喜欢它们)的最大好处是,以后更容易进入并向分支添加一些额外的逻辑,
if (shouldSomethingBeDone()) {
doSomeStuffToSomething(getTheThingThatNeedsStuffDone());
doSomeAdditionalStuff();
} else {
doSomeStuffToSomething(getTheOtherThingThatNeedsStuffDone());
}
or add another condition:
或添加另一个条件:
if (shouldSomethingBeDone()) {
doSomeStuffToSomething(getTheThingThatNeedsStuffDone());
doSomeAdditionalStuff();
} else if (shouldThisOtherThingBeDone()){
doSomeStuffToSomething(getTheOtherThingThatNeedsStuffDone());
}
So, in the end, it's about convenience for you now (shorter to use :?) vs. convenience for you (and others) later. It's a judgment call... but like all other code-formatting issues, the only real rule is to be consistent, and be visually courteous to those who have to maintain (or grade!) your code.
所以,最终,它是关于方便你现在(更短的使用:?)和方便你(和其他人)以后。这是一个主观判断的问题……但是,与所有其他代码格式问题一样,唯一真正的规则是保持一致,并在视觉上礼貌地对待那些必须维护(或升级)您的代码的人。
(all code eye-compiled)
(所有代码eye-compiled)
#7
4
One thing to recognize when using the ternary operator that it is an expression not a statement.
当使用三元运算符时,需要注意的一点是它是一个表达式而不是一个语句。
In functional languages like scheme the distinction doesn't exists:
在像scheme这样的函数式语言中,这种区别并不存在:
(if (> a b) a b)
(如果(> a b) a b)
Conditional ?: Operator "Doesn't seem to be as flexible as the if/else construct"
条件?:运算符“似乎不像if/else构造那样灵活”
In functional languages it is.
在函数式语言中是这样的。
When programming in imperative languages I apply the ternary operator in situations where I typically would use expressions (assignment, conditional statements, etc).
当用命令式语言编程时,我在通常使用表达式(赋值、条件语句等)的情况下应用三元运算符。
#8
4
While the above answers are valid, and I agree with readability being important, there are 2 further points to consider:
虽然上述答案是有效的,我同意可读性是重要的,但还有两点需要考虑:
- In C#6, you can have expression-bodied methods.
- 在c# 6中,你可以有表达体方法。
This makes it particularly concise to use the ternary:
这使得使用ternary特别简洁:
string GetDrink(DayOfWeek day)
=> day == DayOfWeek.Friday
? "Beer" : "Tea";
- Behaviour differs when it comes to implicit type conversion.
- 当涉及到隐式类型转换时,行为会有所不同。
If you have types T1
and T2
that can both be implicitly converted to T
, then the below does not work:
如果有可以隐式转换为T的类型T1和T2,那么下面的就不起作用了:
T GetT() => true ? new T1() : new T2();
(because the compiler tries to determine the type of the ternary expression, and there is no conversion between T1
and T2
.)
(因为编译器试图确定三元表达式的类型,并且在T1和T2之间没有转换。)
On the other hand, the if/else
version below does work:
另一方面,下面的if/else版本确实有效:
T GetT()
{
if (true) return new T1();
return new T2();
}
because T1
is converted to T
and so is T2
因为T1转化为T, T2也是
#9
4
Sometimes it can make the assignment of a bool value easier to read at first glance:
有时它可以使bool值的赋值第一眼看上去更容易阅读:
// With
button.IsEnabled = someControl.HasError ? false : true;
// Without
button.IsEnabled = !someControl.HasError;
#10
3
If I'm setting a value and I know it will always be one line of code to do so, I typically use the ternary (conditional) operator. If there's a chance my code and logic will change in the future, I use an if/else as it's more clear to other programmers.
如果我正在设置一个值,并且我知道这将始终是一行代码,我通常使用三元(条件)运算符。如果我的代码和逻辑有可能在未来发生变化,我就使用If /else,因为其他程序员更清楚这一点。
Of further interest to you may be the ?? operator.
对你更感兴趣的可能是?操作符。
#11
3
The advantage of the conditional operator is that it is an operator. In other words, it returns a value. Since if
is a statement, it cannot return a value.
条件运算符的优点是它是一个运算符。换句话说,它返回一个值。因为if是一个语句,所以它不能返回一个值。
#12
3
I'd recommend limiting the use of the ternary(?:) operator to simple single line assignment if/else logic. Something resembling this pattern:
我建议将三元(?)运算符的使用限制为简单的单行赋值if/else逻辑。类似这种模式:
if(<boolCondition>) {
<variable> = <value>;
}
else {
<variable> = <anotherValue>;
}
Could be easily converted to:
可以很容易地转换为:
<variable> = <boolCondition> ? <value> : <anotherValue>;
I would avoid using the ternary operator in situations that require if/else if/else, nested if/else, or if/else branch logic that results in the evaluation of multiple lines. Applying the ternary operator in these situations would likely result in unreadable, confusing, and unmanageable code. Hope this helps.
我将避免在需要if/else if/else、嵌套if/else或if/else分支逻辑的情况下使用三元运算符。在这些情况下应用三元运算符可能会导致不可读、混乱和难以管理的代码。希望这个有帮助。
#13
1
There is some performance benefit of using the the ? operator in eg. MS Visual C++, but this is a really a compiler specific thing. The compiler can actually optimize out the conditional branch in some cases.
使用?运营商。MS Visual c++,但这确实是一个特定于编译器的东西。在某些情况下,编译器可以优化条件分支。
#14
1
The scenario I most find myself using it is for defaulting values and especially in returns
我最常使用的场景是针对默认值,尤其是在回报方面
return someIndex < maxIndex ? someIndex : maxIndex;
Those are really the only places I find it nice, but for them I do.
那些是我觉得不错的地方,但对他们来说我是。
Though if you're looking for a boolean this might sometimes look like an appropriate thing to do:
虽然如果你在寻找一个布尔值,这有时看起来是一个合适的做法:
bool hey = whatever < whatever_else ? true : false;
Because it's so easy to read and understand, but that idea should always be tossed for the more obvious:
因为它很容易阅读和理解,但这个想法应该被抛到更明显的位置:
bool hey = (whatever < whatever_else);
#15
1
If you need multiple branches on the same condition, use an if:
如果在同一条件下需要多个分支,请使用If:
if (A == 6)
f(1, 2, 3);
else
f(4, 5, 6);
If you need multiple branches with different conditions, then if statement count would snowball, you'll want to use the ternary:
如果您需要多个具有不同条件的分支,那么如果语句计数会滚雪球式地增加,您将需要使用三元:
f( (A == 6)? 1: 4, (B == 6)? 2: 5, (C == 6)? 3: 6 );
Also, you can use the ternary operator in initialization.
此外,您可以在初始化中使用三元运算符。
const int i = (A == 6)? 1 : 4;
Doing that with if is very messy:
用if来做这件事很麻烦:
int i_temp;
if (A == 6)
i_temp = 1;
else
i_temp = 4;
const int i = i_temp;
You can't put the initialization inside the if/else, because it changes the scope. But references and const variables can only be bound at initialization.
不能将初始化放在if/else中,因为它改变了范围。但是引用和const变量只能在初始化时绑定。
#16
1
The ternary operator can be included within an rvalue, whereas an if-then-else cannot; on the other hand, an if-then-else can execute loops and other statements, whereas the ternary operator can only execute (possibly void) rvalues.
三元运算符可以包含在rvalue中,而if-then-else不能;另一方面,if-then-else可以执行循环和其他语句,而三元运算符只能执行(可能无效)的值。
On a related note, the && and || operators allow some execution patterns which are harder to implement with if-then-else. For example, if one has several functions to call and wishes to execute a piece of code if any of them fail, it can be done nicely using the && operator. Doing it without that operator will either require redundant code, a goto, or an extra flag variable.
与此相关的是,&&和||操作符允许使用if-then-else实现某些执行模式,而这些执行模式很难实现。例如,如果有几个函数要调用并希望在其中任何一个失败时执行一段代码,可以使用&& &操作符很好地完成。在没有操作符的情况下进行操作,将需要冗余代码、goto或额外的标志变量。
#17
0
With C# 7, you can use the new ref locals feature to simplify the conditional assignment of ref-compatible variables. So now, not only can you do:
使用c# 7,您可以使用新的ref局部特性来简化与ref兼容的变量的条件分配。所以现在,你不仅可以做到:
int i = 0;
T b = default(T), c = default(T);
// initialization of C#7 'ref-local' variable using a conditional r-value⁽¹⁾
ref T a = ref (i == 0 ? ref b : ref c);
...but also the extremely wonderful:
…但也非常精彩:
// assignment of l-value⁽²⁾ conditioned by C#7 'ref-locals'
(i == 0 ? ref b : ref c) = a;
That line of code assigns the value of a
to either b
or c
, depending on the value of i
.
这行代码将a的值赋给b或c,这取决于i的值。
Notes
1. r-value is the right-hand side of an assignment, the value that gets assigned.
2. l-value is the left-hand side of an assignment, the variable that receives the assigned value.