条件运算符
1
件运算符 (?:) 根据布尔型表达式的值返回两个值中的一个。条件运算符的格式如下
2
3
复制代码
4
condition ? first_expression : second_expression;
5
6
7
备注
8
如果条件为 true,则计算第一表达式并以它的计算结果为准;如果为 false,则计算第二表达式并以它的计算结果为准。只计算两个表达式中的一个。
9
10
使用条件运算符,可以更简洁、雅观地表达那些否则可能要求 if-else 结构的计算。例如,为在 sin 函数的计算中避免被零除,可编写为
11
12
复制代码
13
if(x != 0.0) s = Math.Sin(x)/x; else s = 1.0;
14
15
16
或使用条件运算符,
17
18
复制代码
19
s = x != 0.0 ? Math.Sin(x)/x : 1.0;
20
21
22
条件运算符为右联运算符,因此该形式的表达式
23
24
复制代码
25
a ? b : c ? d : e
26
27
28
按如下规则计算:
29
30
复制代码
31
a ? b : (c ? d : e)
32
33
34
而不是按照下面这样计算:
35
36
复制代码
37
(a ? b : c) ? d : e
38
39
40
不能重载条件运算符。
41
42
示例
43
复制代码
44
// cs_operator_conditional.cs
45
using System;
46
class MainClass
47
{
48
static double sinc(double x)
49
{
50
return x != 0.0 ? Math.Sin(x)/x : 1.0;
51
}
52
53
static void Main()
54
{
55
Console.WriteLine(sinc(0.2));
56
Console.WriteLine(sinc(0.1));
57
Console.WriteLine(sinc(0.0));
58
}
59
}
60
61
62
输出
63
64
0.993346653975306
65
0.998334166468282
66
1
67
68
件运算符 (?:) 根据布尔型表达式的值返回两个值中的一个。条件运算符的格式如下 2

3
复制代码 4
condition ? first_expression : second_expression;5
6

7
备注8
如果条件为 true,则计算第一表达式并以它的计算结果为准;如果为 false,则计算第二表达式并以它的计算结果为准。只计算两个表达式中的一个。9

10
使用条件运算符,可以更简洁、雅观地表达那些否则可能要求 if-else 结构的计算。例如,为在 sin 函数的计算中避免被零除,可编写为11

12
复制代码 13
if(x != 0.0) s = Math.Sin(x)/x; else s = 1.0;14
15

16
或使用条件运算符,17

18
复制代码 19
s = x != 0.0 ? Math.Sin(x)/x : 1.0;20
21

22
条件运算符为右联运算符,因此该形式的表达式23

24
复制代码 25
a ? b : c ? d : e26
27

28
按如下规则计算:29

30
复制代码 31
a ? b : (c ? d : e)32
33

34
而不是按照下面这样计算:35

36
复制代码 37
(a ? b : c) ? d : e38
39

40
不能重载条件运算符。41

42
示例43
复制代码 44
// cs_operator_conditional.cs45
using System;46
class MainClass47
{48
static double sinc(double x) 49
{50
return x != 0.0 ? Math.Sin(x)/x : 1.0;51
}52

53
static void Main() 54
{55
Console.WriteLine(sinc(0.2));56
Console.WriteLine(sinc(0.1));57
Console.WriteLine(sinc(0.0));58
}59
}60
61

62
输出63
64
0.99334665397530665
0.99833416646828266
167
68




浙公网安备 33010602011771号