日期:2013-01-30  浏览次数:20454 次

1。7 语句(Statements)

c#借用了c/c++大多数的语句方法,不过仍然有些值得注意的地方。还有些地方是有所改动的。
在这里,我只提一些c#特有的东东。

1。7。10 “foreach”语句
“foreach”语句列举一个集合内的所有元素,并对这些元素执行一系列的操作。还是看看例子吧:*/

using System;
using System.Collections;
class Test
{
static void WriteList(ArrayList list) {
foreach (object o in list)
{
int i = (int) o;//如果是for语句,这里一定会报错!
Console.WriteLine(0);
Console.WriteLine(++i);
}
}
static void Main() {
ArrayList list = new ArrayList();
for (int i = 0; i < 10; i++)
list.Add(i);
WriteList(list);
}
}
/*这个例子用“foreach”扫描了整个“list”,并把“list”中所有的元素打印出来。有时候还是
挺方便的。

1。7。15 安全检查开关(The checked and unchecked statements)
“checked”和“unchecked”语句用来控制数学运算和完整类型转换的检查工作。“checked”检查它
作用的域中可能出现的违例,并抛出一个异常;而“unchecked”则阻止所有的检查。举个例子:*/

using System;
class Test
{
static int x = 1000000;
static int y = 1000000;
static int F() {
checked {return (x * y);} // 抛出 OverflowException
}
static int G() {
unchecked {return (x * y);} // 返回 -727379968
}
static int H() {
return x * y; // 缺省状态。
}
static void Main() {
F(); //可以注销掉此行试试。
Console.WriteLine(G());
Console.WriteLine(H());
}
}

/*
在编译过程中不会有任何错误出现。因为“checked”和“unchecked”只在运行时才起作用。值得一说的是
H()。它的缺省状态和编译器当前的缺省溢出检查的状态有关。但返回的结果肯定和F()或G()中的任一个相同。
再看一个例子:*/

using System;
class Test
{
const int x = 1000000;
const int y = 1000000;
static int F() {
checked {return (x * y);} // 编译器警告(Compile warning):溢出(overflow)
}
static int G() {
unchecked {return (x * y);} // 返回 -727379968
}
static int H() {
return x * y; // 编译器警告(Compile warning):溢出(overflow)
}
static void Main() {
Console.WriteLine(F()); //可以注销掉此行试试。
Console.WriteLine(G());
Console.WriteLine(H()); //可以注销掉此行试试。
}
}

/* 当F()和H()求值的时候,就会引起一个编译警告。而在G()中,因为有了“unchecked”,屏蔽了这个警
告。要注意的是“checked”和“unchecked”都不能对函数的返回值进行操作!比如:*/
class Test
{
static int Multiply(int x, int y) {
return x * y;
}
static int F() {
checked{ return Multiply(1000000, 1000000); } // 与 return Multiply(1000000, 1000000);
} // 有相同的效果。
}
/* 其实大家稍微想一下知道为什么m$没有这么做!对这个内容的讨论超出本文的范围和俺的能力之外哦。

在c#中,所有的十六进制数都是uint。如果用强制类型转换会引起编译器报错。用“unchecked”则可以
跳过这个机制,把uint的十六进制数转化为int。如:*/

class Test
{
public const int AllBits = unchecked((int)0xFFFFFFFF);
public const int HighBit = unchecked((int)0x80000000);
}

/* 上例所有的常数都是uint,而且超过了int的范围,没有“unchecked”,这种转换会引发一个编译器错
误。注意:上面用的是“unchecked”操作符。不是语句。不过它们之间除了一个用“()”,另一个用
“{}”以外,几乎一样。BTW,“checked”同样。

1。7。16 “lock”语句(The lock statement)
“lock”获得一个相互排斥的对象锁定。(俺查过一些资料,但都没有清晰说明,暂不介绍)