C# 中 If-Else 簡寫
Harshit Jindal
2023年10月12日
Csharp
Csharp Operators
If-Else 語句用於執行條件程式碼塊。我們在 if 塊中指定一個條件。在滿足該條件時,執行 if 程式碼塊。
否則,執行 else 程式碼塊。本教程將介紹三元運算子 ?:,即 C# 中的 if-else 簡寫。
在 C# 中使用三元運算子
三元運算子之所以得名,是因為它需要三個引數作為輸入:條件、if 程式碼塊和 else 程式碼塊。
這三個都包裹在一行簡寫中,使程式碼簡潔明瞭。它有助於在極簡程式碼中實現與 if-else 相同的功能。
using System;
class Program {
public static void Main() {
int exp1 = 5;
double exp2 = 3.0;
bool condition = 5 > 2;
var ans = condition ? exp1 : exp2;
Console.WriteLine(ans);
}
}
輸出:
5
在上面的示例中,三元運算子將首先評估給定條件。如果指定條件為 true,我們移動到 exp1,用 ? 分隔條件。否則,我們移動到 exp2,與 exp1 用 : 分隔。
三元運算子的威力並不止於此,因為我們知道 if-else 語句可以巢狀。三元運算子也可以用更少的程式碼實現相同的目的。
在 C# 中使用巢狀三元運算子
using System;
class Program {
public static void Main() {
int alcoholLevel = 90;
string message = alcoholLevel >= 100
? "You are too drunk to drive"
: (alcoholLevel >= 80 ? "Come on live a little" : "Sober :)");
Console.WriteLine(message);
}
}
輸出:
Come on live a little
在上面的示例中,我們使用巢狀的三元運算子根據一個人的酒精度輸出多條訊息,所有訊息都打包在一行程式碼中。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Harshit Jindal
Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.
LinkedIn