在 C# 中,什麼是三元運算子/條件運算子?
三元運算子是 C# 中的一個條件運算子。它採用三個引數並對布林表示式進行求值。
例如 −
y = (x == 1) ? 70 : 100;
以上,如果第一個運算元求值為 true (1),則對第二個運算元進行求值。如果第一個運算元求值為 false (0),則對第三個運算元進行求值。
以下是一個示例 −
示例
using System; namespace DEMO { class Program { static void Main(string[] args) { int a, b; a = 10; b = (a == 1) ? 20 : 30; Console.WriteLine("Value of b is {0}", b); b = (a == 10) ? 20 : 30; Console.WriteLine("Value of b is {0}", b); Console.ReadLine(); } } }
輸出
Value of b is 30 Value of b is 20
廣告