freeCodeCamp/guide/chinese/csharp/ternary-operator/index.md

41 lines
800 B
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

---
title: Ternary operator
localeTitle: 三元运算符
---
# 三元运算符( `?:` :)
三元运算符根据条件返回两个表达式中的一个。它可以用作if ... else语句的快捷方式。
## 句法
```
condition_expression ? expression_1 : expression_2
```
### 参数
`condition_expression` 布尔表达式。
`expression_1` 如果`condition_expression`为true则返回。
`expression_2` 如果`condition_expression`为false则返回。
## 例
```
// initialize - set true or false here to view different result
bool hasFreeSweet = false;
string str = hasFreeSweet ? "Free sweet!" : "No free sweet.";
//output in console
Console.WriteLine(str);
```
## 产量
```
if hasFreeSweet == true
> Free sweet!
if hasFreeSweet == false
> No free sweet.
```