一、什麼是C#三元表達式
C#三元表達式是一種簡短的if-else語句的簡寫形式,語法為condition ? true_expression : false_expression
。其中,condition代表一個條件表達式,true_expression代表當條件為真時的表達式,false_expression代表當條件為假時的表達式。
二、C#三元表達式的用法
使用C#三元表達式可以簡化複雜的if-else語句的書寫,使代碼更加簡潔,提高代碼的可讀性。
舉個例子,如下面這段代碼:
int a = 5; int b; if (a > 10) { b = 1; } else { b = 2; }
可以使用三元表達式改寫成:
int a = 5; int b = a > 10 ? 1 : 2;
使用三元表達式還可以嵌套使用,如下面這段代碼:
int a = 5; int b; if (a >= 0) { if (a < 10) { b = 1; } else { b = 2; } } else { b = 0; }
可以使用三元表達式改寫成:
int a = 5; int b = a >= 0 ? (a < 10 ? 1 : 2) : 0;
三、C#三元表達式的示例代碼
1、使用三元表達式改寫if-else語句
int x = 5; int y = x < 10 ? 1 : 2; Console.WriteLine(y); // 輸出結果為1
2、使用三元表達式判斷字元串為空
在C#中,判斷字元串是否為空,可以使用string.IsNullOrEmpty()方法,也可以使用三元表達式。
string str = ""; bool isNull = string.IsNullOrEmpty(str) ? true : false; Console.WriteLine(isNull); // 輸出結果為true
3、使用三元表達式判斷是否為偶數
int num = 5; string result = num % 2 == 0 ? "偶數" : "奇數"; Console.WriteLine(result); // 輸出結果為奇數
4、使用三元表達式判斷年齡是否大於等於18歲
int age = 20; bool isAdult = age >= 18 ? true : false; Console.WriteLine(isAdult); // 輸出結果為true
5、使用三元表達式判斷兩個數的大小關係
int a = 10; int b = 5; string result = a > b ? "a大於b" : a == b ? "a等於b" : "a小於b"; Console.WriteLine(result); // 輸出結果為a大於b
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/186063.html