?: 运算符(C# 参考)

条件运算符 (?:) 根据 Boolean 表达式的值返回两个值之一。下面是条件运算符的语法。

condition ? first_expression : second_expression;

备注

condition 的计算结果必须为 truefalse。如果 conditiontrue,则将计算 first_expression 并使其成为结果。如果 conditionfalse,则将计算 second_expression 并使其成为结果。只计算两个表达式之一。

first_expressionsecond_expression 的类型必须相同,或者必须存在从一种类型到另一种类型的隐式转换。

你可通过使用条件运算符表达可能更确切地要求 if-else 构造的计算。例如,以下代码首先使用 if 语句,然后使用条件运算符将整数分类为正整数或负整数。


int input = Convert.ToInt32(Console.ReadLine());
string classify;

// if-else construction.
if (input > 0)
    classify = "positive";
else
    classify = "negative";

// ?: conditional operator.
classify = (input > 0) ? "positive" : "negative";

条件运算符为右联运算符。表达式 a ? b : c ? d : e 作为 a ? b : (c ? d : e) 而非 (a ? b : c) ? d : e 进行计算。

无法重载条件运算符。

class ConditionalOp
{
    static double sinc(double x)
    {
        return x != 0.0 ? Math.Sin(x) / x : 1.0;
    }

    static void Main()
    {
        Console.WriteLine(sinc(0.2));
        Console.WriteLine(sinc(0.1));
        Console.WriteLine(sinc(0.0));
    }
}
/*
Output:
0.993346653975306
0.998334166468282
1
*/

请参阅

C# 参考

C# 编程指南

C# 运算符

if-else(C# 参考)