If you want to execute two different blocks of code based on the result of a Boolean expression, you can use the IF statement.
Understanding the syntax of an if statement
The syntax format of the IF statement is as follows (if and else is the keyword):
if ( booleanExpression )
statement-1;
else
statement-2;
If the booleanexpression evaluates to True, the statement-1 is run, otherwise the statement-2 is run. The Else keyword and subsequent statement-2 are optional. If there is no else clause, then nothing happens if the booleanexpression is false.
For example, the following if statement is used to increment the second hand of a stopwatch (temporarily ignoring minutes). If the value of the seconds is 59, reset to 0, otherwise use the operator + + to increment:
int seconds;
...
if (seconds == 59)
seconds = 0;
else
seconds++;
只使用布尔表达式!
if语句中的表达式必须放在一对圆括号中。除此之外,表达式必须是布尔表达式。在另一些语言中(尤其是C和C++),还可以使用一个整数表达式,编译器能自动将整数值转换成true(非零值)或false(零值)。C#不允许这样做。如果写这样的一个表达式,编译器会报错。
假如在if语句中不慎写了一个赋值表达式,而不是执行一个相等性测试,C#编译器也能识别你的错误。例如:
int seconds;
...
if (seconds = 59) // 编译时错误
...
if (seconds == 59) // 正确
不慎而写成赋值表达式,是C和C++程序容易出现bug的另一个原因。在C和C++中,会将所赋的值(59)悄悄地转换成一个布尔值(任何非零的值都会被视为true),造成每次都必定执行if语句之后的代码。
最后,可以将一个布尔变量作为表达式使用,如下例所示:
bool inWord;
...
if (inWord == true) // 可以,但不常用
...
if (inWord) // 更好
Use blocks to group statements
Sometimes, you need to run two or more statements if a Boolean expression is true. You can group the statements that you want to run into a new method, and then call that method. However, a simpler approach is to group the statements into a block. A block is a series of statements that are closed with a pair of curly braces. In the following example, two statements reset the seconds variable to zero and increment the minutes variable. We use a block to group the two statements. If the value of seconds equals 59, the block is executed:
int seconds = 0;
int minutes = 0;
...
if (seconds == 59)
{
seconds = 0;
minutes++;
}
else
seconds++;
Important Note If the braces are omitted, two serious consequences will be caused. First, the C # compiler associates only the first statement (seconds=0) with an if statement, and the Next statement (minutes++) will no longer be part of the IF statement. Second, when the compiler encounters the Else keyword, it is not associated with the previous if statement, so a syntax error is reported.