条件执行语句

if语句

1
2
3
4
5
6
7
8
if (<test>)
{
<code executed if <test> is true>;
}
else
{
<code executed if >test> is false>;
}

if…else语句

1
2
3
4
5
6
7
8
9
10
11
12
if (var1 == 1)
{
// Do somthing
}
else if (var1 < 1)
{
// Do somthing
}
else
{
// Do somthing
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
if (var1 == 1)
{
// Do somthing.
}
else
{
if (var < 1)
{
// Do somthing
}
else
{
// Do somthing
}
}

switch语句

1
2
3
4
5
6
7
8
9
10
11
12
13
switch (<testVal>)
{
case <comparisonVal1>:
<code to execute if <testVal> == <comparisonVal1>>;
break;
case <comparisonVal2>;
<code to execute if <testVal> == <comparisonVal2>>;
break;
...
default:
<code to execute if <testVal> != <comparisionVals>;
break;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
for( int x=1; x<6; x++ ) 
{
switch( x )
{
case 2:
Console.WriteLine($"x is { x } -- In Case 2");
break;
case 5:
Console.WriteLine($"x is { x } -- In Case 5");
break;
default:
Console.WriteLine($"x is { x } -- In Default case");
break;
}
}
1
2
3
4
5
x is 1 -- In Default case 
x is 2 -- In Case 2
x is 3 -- In Default case
x is 4 -- In Default case
x is 5 -- In Case 5

循环语句

while语句

1
2
3
4
while (<Test>)
{
<code to looped>
}

do循环

1
2
3
4
do
{
<code to be looped>
} while(<Test>);

for循环

1
2
3
4
for(<initialization>; <condition>; <operation>)
{
<code to loop>
}

等价于

1
2
3
4
5
6
<initialization>;
while(<condition>)
{
<code to loop>;
<operation>;
}

for语句中变量的作用域

初始化和迭代表达式中的多表达式

1
2
3
4
5
6
7
8
static void Main()
{
const int MaxI = 5;
for(int i = 0m, j = 10; i < MaxI; i++, j += 10)
{
Console.WriteLine($"{i}, {j}");
}
}

跳转语句

  • break:立即终止循环
  • continue:立即终止当前的循环(执行下一次循环)
  • return:跳出循环及包含该循环的函数

break语句

continue语句

goto语句

1
2
3
4
5
6
7
8
9
10
11
bool thingsAreFine; 
while (true)
{
thingsAreFine = GetNuclearReactorCondition();
if (thingsAreFine)
Console.WriteLine("Things are fine.");
else
goto NotSoGood;
}

NotSoGood: Console.WriteLine("We have a problem.");

using语句

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System; //using 指令,不是 using 语句 
using System.IO; //using 指令,不是 using 语句

namespace UsingStatement
{
class Program
{
static void Main()
{
//using 语句
using (TextWriter tw = File.CreateText("Lincoln.txt"))
{
tw.WriteLine("Four score and seven years ago, ...");
}

//using 语句
using (TextReader tr = File.OpenText("Lincoln.txt"))
{
string InputString;
while (null != (InputString = tr.ReadLine()))
Console.WriteLine(InputString);
}
}
}
}

其他语句

语句 描述
checkedunchecked 控制溢出检查上下文
foreach 遍历一个集合的每个成员
trythrowfinally 处理异常
return 将控制返回到调用函数的成员,而且还能返回一个值
yield 用于迭代