三元運算子

根據布林表示式的值返回兩個值中的一個。

句法:

condition ? expression_if_true : expression_if_false;

例:

string name = "Frank";
Console.WriteLine(name == "Frank" ? "The name is Frank" : "The name is not Frank");

三元運算子是右關聯的,允許使用複合三元表示式。這是通過在父三元方程的真或假位置新增額外的三元方程來完成的。應注意確保可讀性,但在某些情況下這可能是有用的速記。

在此示例中,複合三元運算評估 clamp 函式,如果它在範圍內則返回當前值,如果低於範圍則返回 min 值,如果高於範圍則返回 max 值。

light.intensity = Clamp(light.intensity, minLight, maxLight);

public static float Clamp(float val, float min, float max)
{
    return (val < min) ? min : (val > max) ? max : val;
}

三元運算子也可以巢狀,例如:

a ? b ? "a is true, b is true" : "a is true, b is false" : "a is false"

// This is evaluated from left to right and can be more easily seen with parenthesis:

a ? (b ? x : y) : z

// Where the result is x if a && b, y if a && !b, and z if !a

在編寫複合三元語句時,通常使用括號或縮排來提高可讀性。

expression_if_trueexpression_if_false 的型別必須相同,或者必須存在從一個到另一個的隱式轉換。

condition ? 3 : "Not three"; // Doesn't compile because `int` and `string` lack an implicit conversion.

condition ? 3.ToString() : "Not three"; // OK because both possible outputs are strings.

condition ? 3 : 3.5; // OK because there is an implicit conversion from `int` to `double`. The ternary operator will return a `double`.

condition ? 3.5 : 3; // OK because there is an implicit conversion from `int` to `double`. The ternary operator will return a `double`.

型別和轉換要求也適用於你自己的類。

public class Car
{}

public class SportsCar : Car
{}

public class SUV : Car
{}

condition ? new SportsCar() : new Car(); // OK because there is an implicit conversion from `SportsCar` to `Car`. The ternary operator will return a reference of type `Car`.

condition ? new Car() : new SportsCar(); // OK because there is an implicit conversion from `SportsCar` to `Car`. The ternary operator will return a reference of type `Car`.

condition ? new SportsCar() : new SUV(); // Doesn't compile because there is no implicit conversion from `SportsCar` to SUV or `SUV` to `SportsCar`. The compiler is not smart enough to realize that both of them have an implicit conversion to `Car`.

condition ? new SportsCar() as Car : new SUV() as Car; // OK because both expressions evaluate to a reference of type `Car`. The ternary operator will return a reference of type `Car`.