语句 示例
语句列表和块语句 static void main() {
f();
g();
{
h();
i();
}
}
标记语句和 goto 语句 static void main(string[] args) {
if (args.length == 0)
goto done;
console.writeline(args.length);
done:
console.writeline("done");
}
局部常数声明 static void main() {
const float pi = 3.14f;
const int r = 123;
console.writeline(pi * r * r);
}
局部变量声明 static void main() {
int a;
int b = 2, c = 3;
a = 1;
console.writeline(a + b + c);
}
表达式语句 static int f(int a, int b) {
return a + b;
}
static void main() {
f(1, 2); // expression statement
}
if 语句 static void main(string[] args) {
if (args.length == 0)
console.writeline("no args");
else
console.writeline("args");
}
switch 语句 static void main(string[] args) {
switch (args.length) {
case 0:
console.writeline("no args");
break;
case 1:
console.writeline("one arg ");
break;
default:
int n = args.length;
console.writeline("{0} args", n);
break;
}
}
while 语句 static void main(string[] args) {
int i = 0;
while (i < args.length) {
console.writeline(args[i]);
i++;
}
}
do 语句 static void main() {
string s;
do { s = console.readline(); }
while (s != "exit");
}
for 语句 static void main(string[] args) {
for (int i = 0; i < args.length; i++)
console.writeline(args[i]);
}
foreach 语句 static void main(string[] args) {
foreach (string s in args)
console.writeline(s);
}
break 语句 static void main(string[] args) {
int i = 0;
while (true) {
if (i == args.length)
break;
console.writeline(args[i++]);
}
}
continue 语句 static void main(string[] args) {
int i = 0;
while (true) {
console.writeline(args[i++]);
if (i < args.length)
continue;
break;
}
}
return 语句 static int f(int a, int b) {
return a + b;
}
static void main() {
console.writeline(f(1, 2));
return;
}
throw 语句和 try 语句 static int f(int a, int b) {
if (b == 0)
throw new exception("divide by zero");
return a / b;
}
static void main() {
try {
console.writeline(f(5, 0));
}
catch(exception e) {
console.writeline("error");
}
}
checked 和 unchecked 语句 static void main() {
int x = int32.maxvalue;
console.writeline(x + 1); // overflow
checked {
console.writeline(x + 1); // exception
}
unchecked {
console.writeline(x + 1); // overflow
}
}
lock 语句 static void main() {
a a = ...;
lock(a) {
a.p = a.p + 1;
}
}
using 语句 static void main() {
using (resource r = new resource()) {
r.f();
}
}
新闻热点
疑难解答