跳转到内容

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
华夏公益教科书