基本语句
基本语句:块、声明语句、表达式语句、选择语句(条件语句)、迭代语句(循环语句)、跳转语句。
一 选择语句
1、if 语句
if(condition)
statement(s)
else
statement(s)
2、switch 语句
switch (integerA)
{
case 1:
statement(s)
break;
case2:
statement(s)
break;
default:
statement(s)
break;
}
二 循环语句
1、for 语句
for(initializer;condition;iterator)
statement(s)
2、 while 语句
while(condition)
statement(s)
3、 do...while 语句
do{
statement(s)
}while(condition)
4、foreach 语句
foreach ( int temp in arrayOfInts)
statement(temp)
相当于delphi里的 for...in
三 跳转语句
1、 goto 语句
goto lable1;
statement(not excuted)
Label1:
statement(excuted)
goto语句不能退出try..catch块后面的finally块。
2、 break 语句
退出循环语句,或是退出switch语句。
3、 continue 语句
退出当前循环,进入下一次循环。
4、 return 语句
退出方法。
5、 yield 语句
在迭代器块中用于向枚举数对象提供值或发出迭代结束信号,
yield 语句只能出现在 iterator 块中,该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制:
yield 语句不能出现在匿名方法中。当和 expression 一起使用时,yield return 语句不能出现在 catch 块中或含有一个或多个 catch 子句的 try 块中。
例:
using System;
using System.Collections;
class testYield
{
static void Main(string[] args)
{
if (args.Length != 2) {
throw new Exception("Two numbers required");
}
int x=int.Parse(args[0]);
int y=int.Parse(args[1]);
foreach(int z in QiuMi(x,y))
{
Console.WriteLine(z);
}
}
static IEnumerable QiuMi(int x,int y){
int counter=0 ;
int result=1;
while (counter < y)
{
result = result * x;
yield return result ;
counter++;
}
}
}
运行结果:testyield 2 3
2
4
8
6、 using 语句
定义一个范围,将在此范围之外释放一个或多个对象。
C# 通过 .NET Framework 公共语言运行库 (CLR) 自动释放用于存储不再需要的对象的内存。内存的释放具有不确定性;一旦 CLR 决定执行垃圾回收,就会释放内存。但是,通常最好尽快释放诸如文件句柄和网络连接这样的有限资源。
using 语句允许程序员指定使用资源的对象应当何时释放资源。为 using 语句提供的对象必须实现 IDisposable 接口。此接口提供了 Dispose 方法,该方法将释放此对象的资源。
可以在到达 using 语句的末尾时,或者在该语句结束之前引发了异常并且控制权离开语句块时,退出 using 语句。
例:
using System;
using System.IO;
class test
{
static void Main()
{
using(TextWriter w = File.CreateText("test.txt")){
w.WriteLine("Line one");
w.WriteLine("Line two");
w.WriteLine("Line three");
}
}
}
运行结果:生成一个test.txt文件,内容为
Line one
Line two
Line three

浙公网安备 33010602011771号