程序的活动是通过语句(statement)来表达的。C#支持几种不同的语句,许多语句是以嵌入语句的形式定义的。
声明语句(declaration statement)用于声明局部变量和常量。
表达式语句(expression statement)用于运算表达式。表达式可以作为语句使用译注3,包括方法调用、使用new运算符进行对象分配、使用“=”和复合赋值运算符进行赋值,以及使用“++”和“--”运算符进行增量和减量的运算。
选择语句(selection statement)用于根据某个表达式的值,选择执行若干可能语句中的某一个。这一组语句有if和switch语句。
迭代语句(iteration statement)用于重复执行嵌入语句。这一组语句有while,do,for和foreach语句。
checked和unchecked语句用于控制整型算术运算和转换的溢出检查上、下文。
using语句用于获取一个资源,执行一个语句,然后处理该资源。
表1.5列出了C#的语句,并逐个提供了示例。
表1.5 C#的语句
语 句 | 示 例 |
return语句 | static int Add(int a, int b){ return a + b; } static void Main(){ Console.WriteLine(Add(1, 2)); return; } |
throw和try语句 | static double Divide(double x, double y) { if (y == 0) throw new DivideByZeroException(); return x / y; } static void Main(string[] args){ try{ if (args.Length !=2){ throw new Exception("Two numbers required"); } double x = double.Parse(args[0]); double y = double.Parse(args[1]); Console.WriteLine(Divide(x, y)); } catch (Exception e) { Console.WriteLine(e.Message); } } |
checked和unchecked语句 | static void Main(){ int i = int.MaxValue; checked { Console.WriteLine(i + 1); //异常 } unchecked { Console.WriteLine(i + 1); //溢出 } } |
lock语句 | class Aclearcase/" target="_blank" >ccount { decimal balance; public void Withdraw(decimal amount) { lock(this) { if (amount > balance) { throw new Exception("Insufficient funds"); } balance -= amount; } } } |
using语句 | static void Main(){ using (TextWriter w = File.CreateText("test.txt")) { w.WriteLine("Line one"); w.WriteLine("Line two"); w.WriteLine("Line three"); } } |