
C# 條件句 (c# 教學) – 條件句在編碼上隨處可見. 程式編碼就是一堆分別判斷情況, 再提出行動指令的邏輯. if為邏輯的根本. 就好像一個人去計劃做一件事或對一件事作預備, 不可能無假設, 沒有如果這字眼, 不用if這字眼, 就無法把情況判斷, 分類, 也無法寫程式. 總而言之, 學條件句為最基本而必要的步驟.
if的邏輯方法
- 一個條件句有三個元件, 一是variable, 二是比較項, 三是比較值(可為variable).
- 如 “if(x > 10)”, “x”為variable, “>”為比較邏輯, “10”為比較值. 其句意思為如果x大於10, 就會返回True值至if Statement, 之後就會執行if block內的code.
- variable必須為一個attribute, 因為attribute的數值可以變化, 這樣才可與巳定的比較值比較. 要有數值比較, 才有判斷, 才知是否要執行if block.
- 如果variable不用attribute, 用一個hardcode的值去比較, 如20 > 10, 這樣20永遠比10大, 所以結果永遠true. (即(if(20>10) 是等如if (true))), 就根本不用比較了.
- 如果比較的返回值永遠為true, 那這句條件句根本多餘而不用寫, 因為這if的block必然會走, 直接寫block內的code就可以了.
- 反之, 如果永遠為false, 這code內的block永遠不會走, 所以條件句連同block內的code也可不用寫.
if (條件句)在程式的應用
- if為control flow 流程的必要元件, 即相當於人在思考時想”如果情景如此, 就這樣做”的想法. 一個程式流可以由多個if條件句所形成.
- 用在分類上, 就好像水在樹底下自下而上流到葉, 如送信的機構, 會先把信送至一個國家的省總局, 再送至市, 再送至區, 再到確實的住處.
- 加上for loop, Array, Collection, Interface等, 混合應用可大大增強程序結構的簡潔, 並令Logic 可在Flow當中Block內重用.
if的使用方法
- 如果情況固定, 如用在一個界定問題上, 條件句內只用一個variable, 及hardcode一個比較值是會比較好, 因為簡單直觀而容易看. 如現在温度如果過了20度就開冷氣, 很直接而容易理解.
- 而如果用兩個variable, 就會比較抽象, 但會有相對的彈性. 如現在温度如果過了設定A的度就開冷氣(可以有設定B, 設定C, 這可能由於有不同的設定者, 情景). 這對初學者來說會有點困難, 但相信一段短時間就可以習慣.
而本篇暫時只以基礎介紹, 以下為一些例子顯示出 if 用法. Let’s Start!
條件句 condition 條件句是比較variable加比較邏輯加比較值. 邏輯運算元如下: |
i < 20 – 大於 i <= 20 – 大於及等如 i == 20 – 等如 i > 20 – 小於 i >= 20 – 小於及等如 && And (如果第一個條件句巳為錯, 就不會看之後的條件句, 設為false) || Or (如果第一個條件句巳為對, 就不會看之後的條件句, 設為true) & And (不管第一個條件句是否錯, 都會繼續看之後的條件句) | Or (不管第一個條件句是否對, 都會繼續看之後的條件句) ! Not |
句型 |
if(condition){ // block of code to be executed if the condition is True } |
例子 |
if (isTrue == true){ // block of code to be executed if the condition is True } if (isTrue == false){ // block of code to be executed if the condition is True } |
等如 |
if (isTrue){ // block of code to be executed if the condition is True } if (!isTrue){ // block of code to be executed if the condition is True } |
例子 |
if(condition 1){ // block of code to be executed if the condition is True } else if (condition 2) { // block of code to be executed if the condition is True } else { // block of code to be executed if the all other conditions is False } |
如condition 1乎合條件, 行condition 1的block, 之後完結 如condition 1不乎合條件, 行condition 2, 若乎合條件, 行condition 2的block 如condition 2不乎合條件, 行else 的block, 完結 |
條件句加上 && (And) |
bool bnIsUsed = true; bool bnIsSelling = true; if (bnIsUsed == true && bnIsSelling == true) { // block of code to be executed if the condition is True } |
等如 |
bool bnIsUsed = true; bool bnIsSelling = true; if (bnIsUsed && bnIsSelling) { // block of code to be executed if the condition is True } |
等如 |
if (bnIsUsed) { if (bnIsSelling) { // block of code to be executed if the condition is True } } |
等如意思是説, 如果bnIsUsed 及 bnIsSelling都是true 的話, 就會行Block. |
其他相關:
C# 迴圈 – C# For Loop, For Each 的基礎用法 – 減少程式碼, 用BLOCK把程式碼重用起來
C# 迴圈 – While 的基礎用法 – 以C# 迴圈的BLOCK令程序碼重用
參考資料: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/statements/selection-statements