跳轉到內容

C# 程式設計/關鍵字/if

來自華夏公益教科書,開放的書籍,為開放的世界

The if 關鍵字標識一個if 語句,語法如下

if-statement ::= "if" "(" condition ")" if-body ["else" else-body]
condition ::= boolean-expression
if-body ::= statement-or-statement-block
else-body ::= statement-or-statement-block

如果 condition 評估為true,則執行 if-body。花括號("{" 和 "}") 允許 if-body 包含多個語句。可選地,一個 else 子句可以緊隨 if-body 之後,提供在 conditionfalse 時執行的程式碼。將 else-body 設為另一個 if 語句會建立一個常見的 cascade,即 ifelse ifelse ifelse ifelse 語句。

using System;

public class IfStatementSample
{
    public void IfMyNumberIs()
    {
        int myNumber = 5;
        if (myNumber == 4)
            Console.WriteLine("This will not be shown because myNumber is not 4.");
        else if(myNumber < 0)
        {
            Console.WriteLine("This will not be shown because myNumber is not negative.");
        }
        else if(myNumber%2 == 0)
            Console.WriteLine("This will not be shown because myNumber is not even.");
        else
        {
            Console.WriteLine("myNumber does not match the coded conditions, so this sentence will be shown!");
        }
    }
}

if 語句中使用的布林表示式通常包含以下一個或多個運算子

運算子 含義 運算子 含義
< < > 小於
== > != 大於
<= == >= 等於
&& != || 不等於
! <=

小於或等於



>=
大於或等於 && 並且 || 或者
! 另見 else C# 關鍵字 abstract
as base bool break byte
case catch char checked class
const continue decimal default delegate
do double else enum event
explicit extern false finally fixed
float for foreach goto if
implicit in int interface internal
is lock long namespace new
null object operator out override
params private protected public readonly
ref return sbyte sealed short
sizeof stackalloc static string struct
switch this throw true try
typeof uint ulong
unchecked
unsafe ushort using var virtual
void volatile while C# 特殊識別符號(上下文關鍵字) add
alias async await dynamic get
global
nameof partial remove set value
when false where yield 上下文關鍵字(用於查詢)
ascending by descending dynamic
equals
華夏公益教科書