C# - if 語句



一個if語句由一個布林表示式後跟一個或多個語句組成。

語法

C#中if語句的語法如下:

if(boolean_expression) {
   /* statement(s) will execute if the boolean expression is true */
}

如果布林表示式計算結果為true,則執行if語句內部的程式碼塊。如果布林表示式計算結果為false,則執行if語句結束後的第一組程式碼(在閉合花括號之後)。

流程圖

C# if statement

示例

using System;

namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 10;
        
         /* check the boolean condition using if statement */
         if (a < 20) {
            /* if condition is true then print the following */
            Console.WriteLine("a is less than 20");
         }
         Console.WriteLine("value of a is : {0}", a);
         Console.ReadLine();
      }
   }
}

當以上程式碼編譯並執行時,會產生以下結果:

a is less than 20;
value of a is : 10
csharp_decision_making.htm
廣告