跳轉到內容

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

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

關鍵字 else 用於標識else 子句,它屬於一個 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

一個 else 子句緊隨一個 if-body。當 conditionfalse 時,它提供要執行的程式碼。如果將 else-body 設定為另一個 if 語句,則會建立一個常見的 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!");
        }
    }
}

上面的例子只檢查 myNumber 是否小於 0,前提是 myNumber 不等於 4。它依次只檢查 myNumber%2 是否為 0,前提是 myNumber 不小於 0。由於所有條件都不成立,它會執行最終 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 where yield
上下文關鍵字(用於查詢)
ascending by descending equals from
group in into join let
on orderby select where
華夏公益教科書