
- C# 基礎教程
- C# - 首頁
- C# - 概述
- C# - 環境
- C# - 程式結構
- C# - 基本語法
- C# - 資料型別
- C# - 型別轉換
- C# - 變數
- C# - 常量
- C# - 運算子
- C# - 決策
- C# - 迴圈
- C# - 封裝
- C# - 方法
- C# - 可空型別
- C# - 陣列
- C# - 字串
- C# - 結構體
- C# - 列舉
- C# - 類
- C# - 繼承
- C# - 多型
- C# - 運算子過載
- C# - 介面
- C# - 名稱空間
- C# - 預處理器指令
- C# - 正則表示式
- C# - 異常處理
- C# - 檔案 I/O
C# - if...else 語句
一個if語句可以後跟一個可選的else語句,當布林表示式為假時執行。
語法
C#中if...else語句的語法為:
if(boolean_expression) { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ }
如果布林表示式計算結果為true,則執行if塊程式碼,否則執行else塊程式碼。
流程圖

示例
using System; namespace DecisionMaking { class Program { static void Main(string[] args) { /* local variable definition */ int a = 100; /* check the boolean condition */ if (a < 20) { /* if condition is true then print the following */ Console.WriteLine("a is less than 20"); } else { /* if condition is false then print the following */ Console.WriteLine("a is not less than 20"); } Console.WriteLine("value of a is : {0}", a); Console.ReadLine(); } } }
編譯並執行上述程式碼後,將產生以下結果:
a is not less than 20; value of a is : 100
if...else if...else 語句
一個if語句可以後跟一個可選的else if...else語句,這對於使用單個if...else if語句測試各種條件非常有用。
使用if、else if、else語句時,需要注意以下幾點。
一個if語句可以有零個或一個else語句,並且它必須位於任何else if語句之後。
一個if語句可以有零個或多個else if語句,並且它們必須位於else語句之前。
一旦else if語句成功,就不會測試任何剩餘的else if語句或else語句。
語法
C#中if...else if...else語句的語法為:
if(boolean_expression 1) { /* Executes when the boolean expression 1 is true */ } else if( boolean_expression 2) { /* Executes when the boolean expression 2 is true */ } else if( boolean_expression 3) { /* Executes when the boolean expression 3 is true */ } else { /* executes when the none of the above condition is true */ }
示例
using System; namespace DecisionMaking { class Program { static void Main(string[] args) { /* local variable definition */ int a = 100; /* check the boolean condition */ if (a == 10) { /* if condition is true then print the following */ Console.WriteLine("Value of a is 10"); } else if (a == 20) { /* if else if condition is true */ Console.WriteLine("Value of a is 20"); } else if (a == 30) { /* if else if condition is true */ Console.WriteLine("Value of a is 30"); } else { /* if none of the conditions is true */ Console.WriteLine("None of the values is matching"); } Console.WriteLine("Exact value of a is: {0}", a); Console.ReadLine(); } } }
編譯並執行上述程式碼後,將產生以下結果:
None of the values is matching Exact value of a is: 100
csharp_decision_making.htm
廣告