一周学会 C# (语句二)
C# 才鸟( QQ:249178521 )
5. 布尔型操作符
** 1. ** ** 赋值 ** ** = **
** 2. ** ** 等于 ** ** == != **
** 3. ** ** 逻辑 ** ** ** ** ! && || ^ & | ** ** **
** int tens = (9 * 6) / 13; **
** int units = (9 * 6) % 13; **
** bool isFour = tens == 4; **
** bool isTwo = units == 2; **
** bool hhg; **
** hhg = isFour & isTwo; **
** hhg = !(isFour & isTwo); **
** hhg = !isFour | !isTwo; **
** hhg = !hhg; **
&& 的结果是只有当操作符两边的操作数都是 true 时才是 true 。如果 && 左边的操作数是 false 的话,那么不管右边的操作数是 false 还是 true ,整个 && 表达式的值为 false 。
|| 的结果是当操作符两边的操作数只要一个是 true 的时候就是 true 。如果 && 左边的操作数是 true 的话,那么不管右边的操作数是 false 还是 true ,整个 && 表达式的值为 true 。
! 表示取反的意思。
有一种称为“短路”的技术非常有用。例如,左边的表达式可以判断一个值是否为 0 ,然后右边的表达式可以把这个值作为除数。例如:
if ((x != 0) && (y / x > tolerance)) ...
6.if 语句
** string DaySuffix(int days) **
** { **
** string result; **
** if (days / 10 == 1) **
** result = "th"; **
** else if (days % 10 == 1) **
** result = "st"; **
** else if (days % 10 == 2) **
** result = "nd"; **
** else if (days % 10 == 3) **
** result = "rd"; **
** else **
** result = "th"; **
** return result; **
** } **
if 语句的条件表达式必须是纯粹的 bool 型表达式。例如下面的诗句是错误的:
if (currentValue = 0) ...
c# 要求所有的变量必须预先明确赋值后才能使用,因此,下列的程序是错误的:
int m;
if (inRange)
m = 42;
int copy = m; // 错误,因为 m 可能不会被赋初值。
在 C# 中, if 语句中不能包含变量声明语句,例如:
if (inRange)
int useless;// 错误
7.switch 语句
· ** 语法 ** ** **
w ** 用于整数类类型 ** ** **
w ** case ** ** 后的标志必须是编译时为常数 ** ** **
w ** 没有表示范围的缩略形式 ** ** **
** string DaySuffix(int days) **
** { **
** string result = "th"; **
** if (days / 10 != 1) **
** switch (days % 10) **
** { **
** case 1 : **
** result = "st"; break; **
** case 2 : **
** result = "nd"; break; **
** case 3 : **
** result = "rd"; break; **
** default: // ** ** 表示不符合上面条件的情况 **
** result = "th"; break; **
** } **
** return result; **
** } **
你只能对整型、字符串或可以隐式转换为整型或字符串的用户自定义类型使用 switch 语句。 case 标志必须在编译时是常数。
C# 中没有 Visual Basic 中的 Is 关键字在 case 中进行比较,例如:
switch (expression())
{
case Is < 42 : // 错误
case method() : // 错误
}
C# 中没有范围比较符。
switch (expression())
{
case 16 To 21 : // 错误
case 16..21 : // 错误
}
注意:每个 case 段必须包括 break 语句, default 语句也不例外。
8.while/do
** int digit = 0; **
** while (digit != 10) **
** { **
** Console.Write("{0} ", digit); **
** digit++; **
** }// ** ** 没有分号 ** ** **
** int digit = 0; **
** do **
** { **
** Console.Write("{0} ", digit); **
** digit++; **
** } **
** while (digit != 10);// ** ** 有分号 **