声明语句
声明局部变量或常量。声明语句可以出现在块中,但不允许它们作为嵌入语句使用。
- 局部变量声明
- int x = 100;
//声明变量的时候,追加了变量的初始化器。 - int x;
x = 100;
//声明的时候没有初始化,在后面对变量进行了赋值。 - 数组初始化器
- int x = 100;
int[] myArray = { 1, 2, 3 };
Console.WriteLine(myArray[1]);
- 局部常量声明
const int x = 100;
//常量在声明的同时,必须跟上初始化器,给一个初始值
嵌入式语句
包含块语句、表达式语句、选择语句、迭代语句、跳转语句、try语句、checked 语句和 unchecked 语句、lock语句、using语句、yield语句。
表达式语句
用于计算所给定的表达式。由此表达式计算出来的值(如果有)被丢弃。
- 方法调用表达式
Console.WriteLine("Hello World!");
- 对象创建表达式
new Form();
- 赋值语句
int x;
x = 100;
- 后置的自增/自减表达式,前置的自增/自减表达式
int x;
x = 100;
x++;
x--;
++x;
--x;
块语句(简称“块”)
block 用于在只允许使用单个语句的上下文中编写多条语句
- 通常和if语句等结合使用
- 块语句无论什么时候都会被编译器当成一条语句看待
- 编译器认为块语句是一条完整的语句(写完不用加分号)
int x = 100; //作用域在整个main方法
{ //块语句
Console.WriteLine(x);
int y = 200; //作用域在块语句内
Console.WriteLine(y);
}
//Console.WriteLine(y); 访问不到块语句内的y
选择(判断、分支)语句
选择语句会根据表达式的值从若干个给定的语句中选择一个来执行。
- If语句
if 语句根据布尔表达式的值选择要执行的语句。- 每条If语句只能有一个嵌入式语句
- 使用块语句作为If语句的嵌入式语句
int score = Convert.ToInt32(Console.ReadLine());
if (score >=0 && score <= 100)
{
if (score >= 60)
{
Console.WriteLine("Pass");
}
else
{
Console.WriteLine("Failed");
}
}
else
{
Console.WriteLine("Input Error!");
}
int score = Convert.ToInt32(Console.ReadLine());
if (score >=0 && score <= 100)
{
if (score >= 80)
{
Console.WriteLine("A");
}
else if(score >= 60)
{
Console.WriteLine("B");
}
else if (score >= 40)
{
Console.WriteLine("C");
}
else
{
Console.WriteLine("D");
}
}
else
{
Console.WriteLine("Input Error!");
}
- switch语句
switch 语句选择一个要执行的语句列表,此列表具有一个相关联的 switch 标签,它对应于 switch 表达式的值。- case后面必须跟一个常量表达式,不能像If语句分段判断
- switch的表达式的类型不能是浮点类型
//需求:80~100->A; 60~79->B; 40~59->C; 0~39->D; 其他->Error
int score = Convert.ToInt32(Console.ReadLine());
switch (score/10)
{
case 10:
if (score==100)
{
goto case 8;
}
else
{
goto default;
}
case 8:
case 9:
Console.WriteLine("A");
break;
case 6:
case 7:
Console.WriteLine("B");
break;
case 5:
case 4:
Console.WriteLine("C");
break;
case 0:
case 1:
case 2:
case 3:
Console.WriteLine("D");
break;
default:
Console.WriteLine("Error");
break;
class Program
{
static void Main(string[] args)
{
Level myLv = Level.High;
switch (myLv)
{
case Level.High:
Console.WriteLine("High level!");
break;
case Level.Mid:
Console.WriteLine("Mid level!");
break;
case Level.Low:
Console.WriteLine("Low level!");
break;
default:
break;
}
}
}
enum Level
{
High,
Mid,
Low
}
try…catch…finally语句
try 语句提供一种机制,用于捕捉在块的执行期间发生的各种异常。此外,try 语句还能让您指定一个代码块,并保证当控制离开 try 语句时,总是先执行该代码。
class Program
{
static void Main(string[] args)
{
Calculator c = new Calculator();
int r = c.Add("100", "200");
Console.WriteLine(r);
}
}
class Calculator
{
public int Add(string arg1,string arg2)
{
int a = 0;
int b = 0;
bool hasError = false;
try
{
a = int.Parse(arg1);
b = int.Parse(arg2);
}
catch (ArgumentNullException ane) //在异常类型后加标识符
{
//Console.WriteLine("Your argument(s) are null.");
Console.WriteLine(ane.Message); //可以通过该变量访问异常实例
hasError = true;
}
catch (FormatException fe)
{
//Console.WriteLine("Your argument(s) are not a number.");
Console.WriteLine(fe.Message);
hasError = true;
}
catch (OverflowException oe)
{
//Console.WriteLine("Out of range!");
Console.WriteLine(oe.Message);
hasError = true;
}
finally
//finally 块中的语句始终在控制离开 try 语句时执行。无论是什么原因引起控制转移,情况都是如此。
{
if (hasError)
{
Console.WriteLine("Execution has error!");
}
else
{
Console.WriteLine("Done!");
}
}
int result = a + b;
return result;
}
}
迭代(循环)语句
迭代语句重复执行嵌入语句。
包含while语句、do语句、for语句、foreach语句。
- while语句
while 语句按不同条件执行一个嵌入语句零次或多次。
格式: while关键字 (循环条件,布尔类型的表达式)循环体,嵌入式语句
//需求:要求输入两个数字,当两个数字的和等于100时,就加1分,允许进行下一轮。
//直到输入的两个数字和不等于100时,游戏结束,打印出最后得分。
int score = 0;
bool canContinue = true;
while (canContinue)
//当循环条件canContinue为true时,循环体得到执行
{
Console.WriteLine("Please input first number.");
string str1 = Console.ReadLine();
int x = int.Parse(str1);
Console.WriteLine("Please input first number.");
string str2 = Console.ReadLine();
int y = int.Parse(str2);
int sum = x + y;
if (sum == 100)
{
score++;
Console.WriteLine("Correct! {0}+{1}={2}",x,y,sum);
}
else
{
Console.WriteLine("Error! {0}+{1}={2}", x, y, sum);
canContinue = false;
}
}
Console.WriteLine("Your score is {0}.",score);
Console.WriteLine("Game Over!");
- do语句
do 语句按不同条件执行一个嵌入语句一次或多次。
格式:do关键字 循环体 while关键字 (循环条件,布尔类型表达式);
int score = 0;
int sum = 0;
do
{
Console.WriteLine("Please input first number.");
string str1 = Console.ReadLine();
int x = int.Parse(str1);
Console.WriteLine("Please input first number.");
string str2 = Console.ReadLine();
int y = int.Parse(str2);
sum = x + y;
if (sum == 100)
{
score++;
Console.WriteLine("Correct! {0}+{1}={2}", x, y, sum);
}
else
{
Console.WriteLine("Error! {0}+{1}={2}", x, y, sum);
}
} while (sum==100);
Console.WriteLine("Your score is {0}.",score);
Console.WriteLine("Game Over!");
- for语句
for 语句计算一个初始化表达式序列,然后,当某个条件为真时,重复执行相关的嵌入语句并计算一个迭代表达式序列。
for (int count = 0; count < 10; count++)
{
Console.WriteLine("Hello World!");
}
//乘法表
for (int a = 1; a <= 9; a++)
{
for (int b = 1; b <= a; b++)
{
Console.Write("{0}x{1}={2}\t",b,a,a*b);
}
Console.WriteLine();
}
- foreach语句
foreach 语句用于枚举一个集合的元素,并对该集合中的每个元素执行一次相关的嵌入语句。- 最佳应用场合:对集合进行遍历
int[] intArray = new int[] { 1,2,3,4,5,6 };
List<int> intList = new List<int>() { 1, 2, 3, 4, 5, 6 };
foreach (var current in intArray)
//迭代变量的数据类型;迭代变量;集合
{
Console.WriteLine(current);
}
跳转语句
跳转语句用于无条件地转移控制。
包含break语句、continue语句、goto语句、return语句、throw语句。
- continue语句
continue 语句将开始直接封闭它的 while、do、for 或 foreach 语句的一次新迭代。
int score = 0;
int sum = 0;
do
{
Console.WriteLine("Please input first number.");
string str1 = Console.ReadLine();
int x = 0;
try
{
x = int.Parse(str1);
}
catch
{
Console.WriteLine("First number has problem!Restart.");
continue;
}
Console.WriteLine("Please input first number.");
string str2 = Console.ReadLine();
int y = 0;
try
{
y = int.Parse(str2);
}
catch
{
Console.WriteLine("Second number has problem!Restart.");
continue;
}
sum = x + y;
if (sum == 100)
{
score++;
Console.WriteLine("Correct! {0}+{1}={2}", x, y, sum);
}
else
{
Console.WriteLine("Error! {0}+{1}={2}", x, y, sum);
}
} while (sum==100);
Console.WriteLine("Your score is {0}.",score);
Console.WriteLine("Game Over!");
- break语句
break 语句将退出直接封闭它的 switch、while、do、for 或 foreach 语句。
//在第一个数字或第二个数字输入end,手动结束循环,输出分数,游戏结束。
int score = 0;
int sum = 0;
do
{
Console.WriteLine("Please input first number.");
string str1 = Console.ReadLine();
if (str1.ToLower() == "end") //无论end大小写
{
break;
}
int x = 0;
try
{
x = int.Parse(str1);
}
catch
{
Console.WriteLine("First number has problem!Restart.");
continue;
}
Console.WriteLine("Please input first number.");
string str2 = Console.ReadLine();
if (str2.ToLower() == "end")
{
break;
}
int y = 0;
try
{
y = int.Parse(str2);
}
catch
{
Console.WriteLine("Second number has problem!Restart.");
continue;
}
sum = x + y;
if (sum == 100)
{
score++;
Console.WriteLine("Correct! {0}+{1}={2}", x, y, sum);
}
else
{
Console.WriteLine("Error! {0}+{1}={2}", x, y, sum);
}
} while (sum==100);
Console.WriteLine("Your score is {0}.",score);
Console.WriteLine("Game Over!");
- return语句
return 语句会将控制返回到出现 return 语句的函数的当前调用方。- 尽早return原则
- 如果方法的返回值不是void类型,而且方法体中使用了选择语句,就需要保证选择语句当中每个分支都能让这个方法return
static void Main(string[] args)
{
Greeting("Mr.Okay");
}
static string WhoIsWho(string alais)
{
if (alais=="Mr.Okay")
{
return "Tim";
}
else
{
return "I don't know!"; //此处没有return会报错
}
}
static void Greeting(string name)
{
if (string.IsNullOrEmpty(name))
{
return; //一旦发现条件或参数不合格,立刻执行return,使结构、方法变得清晰
}
Console.WriteLine("Hello,{0}!",name);
}