跳转到内容

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