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 之后,提供在 condition 为 false 时执行的代码。将 else-body 设为另一个 if 语句会创建一个常见的 cascade,即 if、else if、else if、else if、else 语句。
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 语句中使用的布尔表达式通常包含以下一个或多个运算符
| 运算符 | 含义 | 运算符 | 含义 |
|---|---|---|---|
| < | < | > | 小于 |
| == | > | != | 大于 |
| <= | == | >= | 等于 |
| && | != | || | 不等于 |
| ! | <= |
小于或等于