?: 运算符 - 三元条件运算符 - C# reference

?: 运算符 - 三元条件运算符 - C# reference

条件运算符 (?:) 也称为三元条件运算符,用于计算布尔表达式,并根据布尔表达式的计算结果为 true 还是 false 来返回两个表达式中的一个结果,如以下示例所示:

string GetWeatherDisplay(double tempInCelsius) => tempInCelsius < 20.0 ? "Cold." : "Perfect!";

Console.WriteLine(GetWeatherDisplay(15)); // output: Cold.

Console.WriteLine(GetWeatherDisplay(27)); // output: Perfect!

如上述示例所示,条件运算符的语法如下所示:

condition ? consequent : alternative

C# 语言参考记录了 C# 语言的最新发布版本。 它还包含即将发布的语言版本公共预览版中功能的初始文档。

本文档标识了在语言的最后三个版本或当前公共预览版中首次引入的任何功能。

提示

若要查找 C# 中首次引入功能时,请参阅 有关 C# 语言版本历史记录的文章。

condition 表达式的计算结果必须为 true 或 false。 若 condition 的计算结果为 true,将计算 consequent,其结果成为运算结果。 若 condition 的计算结果为 false,将计算 alternative,其结果成为运算结果。 只会计算 consequent 或 alternative。 条件表达式是目标类型的。 也就是说,如果条件表达式的目标类型是已知的,则 consequent 和 alternative 的类型必须可隐式转换为目标类型,如以下示例所示:

var rand = new Random();

var condition = rand.NextDouble() > 0.5;

int? x = condition ? 12 : null;

IEnumerable xs = x is null ? new List() { 0, 1 } : new int[] { 2, 3 };

如果条件表达式的目标类型未知(例如使用 var 关键字时)或 consequent 和 alternative 的类型必须相同,或者必须存在从一种类型到另一种类型的隐式转换:

var rand = new Random();

var condition = rand.NextDouble() > 0.5;

var x = condition ? 12 : (int?)null;

条件运算符为右联运算符,即形式的表达式

a ? b : c ? d : e

计算结果为

a ? b : (c ? d : e)

提示

可以使用以下助记键设备记住条件运算符的计算方式:

is this condition true ? yes : no

ref 条件表达式

条件 ref 表达式可有条件地返回变量引用,如以下示例所示:

int[] smallArray = {1, 2, 3, 4, 5};

int[] largeArray = {10, 20, 30, 40, 50};

int index = 7;

ref int refValue = ref ((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]);

refValue = 0;

index = 2;

((index < 5) ? ref smallArray[index] : ref largeArray[index - 5]) = 100;

Console.WriteLine(string.Join(" ", smallArray));

Console.WriteLine(string.Join(" ", largeArray));

// Output:

// 1 2 100 4 5

// 10 20 0 40 50

可以 ref 分配 条件 ref 表达式的结果。 将其用作引用返回,或将其作为 、refoutin、或ref readonly方法参数传递。 还可以分配条件 ref 表达式的结果,如前面的示例所示。

ref 条件表达式的语法如下所示:

condition ? ref consequent : ref alternative

条件 ref 表达式与条件运算符相似,仅计算两个表达式其中之一:consequent 或 alternative。

在 ref 条件表达式中,consequent 和 alternative 的类型必须相同。 ref 条件表达式不由目标确定类型。

条件运算符和 if 语句

当需要有条件地计算值时,使用条件运算符而不是 if 语句 可能会导致更简洁的代码。 下面的示例演示了将整数归类为负数或非负数的两种方法:

int input = new Random().Next(-5, 5);

string classify;

if (input >= 0)

{

classify = "nonnegative";

}

else

{

classify = "negative";

}

classify = (input >= 0) ? "nonnegative" : "negative";

运算符可重载性

用户定义类型不能重载条件运算符。

C# 语言规范

有关详细信息,请参阅 C# 语言规范的条件运算符部分。

较新版本功能的规范如下:

目标类型的条件表达式

另请参阅

简化条件表达式(样式规则 IDE0075)

C# 运算符和表达式

if 语句

%> 和 ?[] 运算符

%> 和 ??= 运算符

ref 关键字

相关推荐

隧道 (電視劇)
365bet足彩官网

隧道 (電視劇)

08-07 252
最公平的传奇游戏推荐
365bet足彩官网

最公平的传奇游戏推荐

08-25 744
15 Tested Homemade Sex Toys for Men – DIY Male Sex Toy Ideas