表达式的定义
-
什么是表达式
- 表达式,是任何一门语言的基本组件(还有命令和声明)之一,表达式是任何一门语言的核心组件
- 表达式是专门用来求值的语法实体,成功的话会得到一个产出值,失败的话会得到一个终值(异常)
- 各种编辑语言对表达式的实现不尽相同,但大体都符合这个定义
-
C#语言对表达式的定义
- 表达式是由一个或多个操作数和零个或多个操作符组成,能得到一个值,目标,方法或名称空间的序列。表达式可能是由字面值,方法调用,操作符和操作数或者简单名字(simple name)组成。simple name可能是变量名,类型成员,方法成员,名称空间或者类型名
- 算法逻辑的最基本(最小)单元,表达一定算法意图
- 因为操作符有优先级,所以表达式也就有了优先级
各类表达式概览
- C#语言中表达式的分类
- A Value.Every value has an associated type.(每个值都具有他的数据类型)任何能得到值的运算
if (3 < 5)//bool型value表达式
{
Console.WriteLine("Hello");
}
- A variable.Every variable has an associated type.
int x = 100;
int y;
y = x;
- A namespace.
System.Windows.Forms.Form myForm;
- A type.
var t = typeof(Int32);
- A method group.例如:Console.Writeline,这是一组方法,重载决策决定具体调用哪一个
Console.WriteLine("Hello");
- A null literal.
Form form = null;
- An anonymous function.
Action action = delegate () { Console.WriteLine("Hello"); };
action();
- A property access.
Form form_1 = new Form();
form_1.Text = "Hello";
form_1.ShowDialog();
- An event access.
namespace Expression
{
class Program
{
static void Main(string[] args)
{
Form form = new Form();
form.Load += Form_Load;
}
private static void Form_Load(object sender, EventArgs e)
{
Form form = sender as Form;
if (form == null)
{
return;
}
form.Text = "New Title";
}
}
}
- An indexer access.
List<int> intlist = new List<int> { 1, 2, 3 };
int a = intlist[2];
- Nothing.对返回值为void的方法的调用
- 复合表达式的求值
- 注意操作符的优先级和同优先级操作符的运算方向
- 参考C#语言定义文档
语句的定义
- Wikipedia对语句的定义
- 语句是命令式编程语言中最小的独立元素,功能是表达一些将被执行的动作。一个高级语言写成的程序是由一系列的语句构成的(使用语句编写程序)。语句还有自己的内部组件(例如:表达式)
- 语句是高级语言的语法——汇编语言和机器语言只有指令(高级语言中的表达式对应低级语言中的指令),语句等价于一个或一组有明显逻辑关联的指令。
- C#语言对语句的定义
- 一个程序所要执行的动作是由语句所表达的。常见的功能包括:声明变量,对变量进行赋值,调用函数,在集合当中进行循环(迭代),通过给定条件在各分支进行跳转(判断语句)。语句在程序中执行的顺序称为控制流(flow of control,即程序逻辑的走向)或意识流(flow of execution)。
- C#语言的语句除了能够让程序员“顺序地”(sequentially)表达算法思想,还能通过条件判断,跳转和循环等方法控制程序逻辑的走向。
- 简言之就是:陈述算法思想,控制逻辑走向,完成有意义的动作(action)。
- C#语言的语句由分号(;)结尾,但由分号结尾的不一定都是语句。如字段的声明(Public int a=1;)
- 语句一定是出现在方法体里
语句详解
语句分为三大类:标号语句(labled-statement),声明语句(declaration-statement),嵌入式语句(embedded-statement)
声明语句(declaration-statement)
namespace Statement
{
class Program
{
static void Main(string[] args)
{
//局部变量的声明
int x;//int为变量的数据类型 x为变量的声明器
var y = 100; //=100为变量的初始化器
int[] myArray = { 1, 2, 3 };//数组变量初始化器
//局部常量的声明
const int z = 200;//常量在声明的同时必须跟上初始化器
}
}
}
嵌入式语句(embedded-statement)包括
- 表达式语句(expression-statement)
namespace Statement
{
class Program
{
static void Main(string[] args)
{
//方法调用表达式
Console.WriteLine("Hello");
//对象创建表达式
new Form();
//赋值语句
int x = 100;
//前置自增表达式
++x;
//前置自减表达式
--x;
//后置自增表达式
x++;
//后置自减表达式
x--;
//await表达式(异步编程使用)
}
}
}
不是所有的表达式都允许作为语句使用,具体而言,不允许像x+y和x==1这样只计算一个值(此值将被放弃)的表达式作为语句使用。例如:
namespace Statement
{
class Program
{
static void Main(string[] args)
{
int x = 100;
int y = 200;
x + y;//C#中无法通过编译。C中可以通过
}
}
}
- 块语句(block)
block由一个扩在大括号内可选statement-list组成。如果没有此语句列表,此块语句为空。
namespace Statement
{
class Program
{
static void Main(string[] args)
{
int x = 100;
{
Console.WriteLine(x);//必须定义在方法体内的花括号才是块语句
int y = 200;
Console.WriteLine(y);
}
Console.WriteLine(y);//变量的作用域 在块语句内的变量无法在块语句外无法使用
}
}
}
- 选择语句(choose-statement)
if语句
namespace Statement
{
class Program
{
static void Main(string[] args)
{
int score = 15;
if (score >= 80 && score <= 100)
{
Console.WriteLine("A");
}
else if(score >= 60)
{
Console.WriteLine("B");
}
else if (score >= 40)
{
Console.WriteLine("C");
}
else if (score >= 0)
{
Console.WriteLine("D");
}
else
{
Console.WriteLine("Input Error");
}
}
}
}
switch语句
如果switch表达式的类型为sbyte,byte,short,ushort,int,uint,long,ulong,bool,char,string或enum-type,或者是对应于以上某种类型的可以为null的类型,则该类型就是switch语句的主导类型。
(*不包括double)
namespace Statement
{
class Program
{
static void Main(string[] args)
{
int score = 65;
switch (score/10)
{
case 10:
if (score == 100)
{
goto case 8;
}
else
{
goto default;
}
break;
case 9:
case 8:
Console.WriteLine("A");
break;
case 7:
case 6:
Console.WriteLine("B");
break;
case 5:
case 4:
Console.WriteLine("C");
break;
case 3:
case 2:
case 1:
case 0:
Console.WriteLine("D");
break;
default:
Console.WriteLine("Input Error");
break;
}
}
}
}
namespace Statement
{
class Program
{
static void Main(string[] args)
{
Level level = new Level();
switch (level)
{
case Level.High:
Console.WriteLine("A");
break;
case Level.Mid:
Console.WriteLine("B");
break;
case Level.Low:
Console.WriteLine("C");
break;
default:
Console.WriteLine("D");
break;
}
}
}
enum Level
{
High,
Mid,
Low
}
}
-
try语句(try-statement)
try语句提供一种机制,用于捕捉在块语句的执行期间发生的各种异常,此外,try语句还能指定一个代码块,并保证当控制离开try语句时,总是先执行该代码。
由三种可能的try语句形式: -
一个try块后接一个或多个catch块
-
一个try块后接一个finally块
-
一个try块后接一个或多个catch块,后面再接一个finally块
namespace Statement
{
class Program
{
static void Main(string[] args)
{
Calcultor c = new Calcultor();
int x = c.Add("abc", "123");//FormatException
int y = c.Add("999999999999999999", "123");//OverflowException
int z = c.Add(null, "123");//ArgumentNullException
Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);
}
}
class Calcultor
{
public int Add(string str1,string str2)
{
int a = 0;
int b = 0;
bool hasError = false;
try
{
a = int.Parse(str1);
b = int.Parse(str2);
}
catch (ArgumentNullException ane)
{
Console.WriteLine(ane.Message);
hasError = true;
}
catch (FormatException fe)
{
Console.WriteLine(fe.Message);
hasError = true;
}
catch(OverflowException oe)
{
Console.WriteLine(oe.Message);
hasError = true;
}
finally//一般把释放系统资源的代码写在finally语句,无论是否有异常都会执行finally语句
//第二个功能便是打log
{
if (hasError)
{
Console.WriteLine("Execution has error!");
}
else
{
Console.WriteLine("Done!");
}
}
int result = a + b;
return result;
}
}
}
throw关键字的用法
namespace Statement
{
class Program
{
static void Main(string[] args)
{
Calcultor c = new Calcultor();
int r = 0;
try
{
int y = c.Add("999999999999999999", "123");//Main方法调用
}
catch (OverflowException oe)//在Main方法中抓住OverflowException,打印log信息
{
Console.WriteLine(oe.Message);
}
Console.WriteLine(r);
}
}
class Calcultor
{
public int Add(string str1,string str2)
{
int a = 0;
int b = 0;
bool hasError = false;
try
{
a = int.Parse(str1);
b = int.Parse(str2);
}
catch (ArgumentNullException ane)
{
Console.WriteLine(ane.Message);
hasError = true;
}
catch (FormatException fe)
{
Console.WriteLine(fe.Message);
hasError = true;
}
catch(OverflowException oe)
{
throw oe;//将OverflowException抛出 谁调用谁处理
}
finally
{
if (hasError)
{
Console.WriteLine("Execution has error!");
}
else
{
Console.WriteLine("Done!");
}
}
int result = a + b;
return result;
}
}
}
- 迭代语句
while语句
namespace Statement
{
class Program
{
static void Main(string[] args)
{
int score = 0;
bool cancontinue = true;
while (cancontinue)
{
Console.WriteLine("Please input first number");
string str1 = Console.ReadLine();
int a = int.Parse(str1);
Console.WriteLine("Please input second number");
string str2 = Console.ReadLine();
int b = int.Parse(str2);
int sum = a + b;
if (sum == 100)
{
score++;
Console.WriteLine("Correct! {0}+{1}={2}",a,b,sum);
}
else
{
Console.WriteLine("Error! {0}+{1}={2}",a,b,sum);
cancontinue = false;
}
}
Console.WriteLine("Your Score is {0}", score);
Console.WriteLine("GameOver");
}
}
}
do-while语句
namespace Statement
{
class Program
{
static void Main(string[] args)
{
int score = 0;
int sum;
do//dowhile语句中的内容会执行一次再判断是否循环 while语句可能一次都不执行
{
Console.WriteLine("Please input first number");
string str1 = Console.ReadLine();
int a = int.Parse(str1);
Console.WriteLine("Please input second number");
string str2 = Console.ReadLine();
int b = int.Parse(str2);
sum = a + b;
if (sum == 100)
{
score++;
Console.WriteLine("Correct! {0}+{1}={2}", a, b, sum);
}
else
{
Console.WriteLine("Error! {0}+{1}={2}", a, b, sum);
}
} while (sum == 100);
Console.WriteLine("Your Score is {0}", score);
Console.WriteLine("GameOver");
}
}
}
continue语句:放弃当前循环,立即执行一下次循环
break语句:跳出循环
namespace Statement
{
class Program
{
static void Main(string[] args)
{
int score = 0;
int a = 0;
int b = 0;
int sum = 0;
do//dowhile语句中的内容会执行一次再判断是否循环 while语句可能一次都不执行
{
Console.WriteLine("Please input first number");
string str1 = Console.ReadLine();
if (str1.ToLower()=="end")
{
break;
}
try
{
a = int.Parse(str1);
}
catch
{
Console.WriteLine("First number has problem,Restart");
continue;
}
Console.WriteLine("Please input second number");
string str2 = Console.ReadLine();
try
{
b = int.Parse(str2);
}
catch
{
Console.WriteLine("Second number has problem,Restart");
continue;
}
sum = a + b;
if (sum == 100)
{
score++;
Console.WriteLine("Correct! {0}+{1}={2}", a, b, sum);
}
else
{
Console.WriteLine("Error! {0}+{1}={2}", a, b, sum);
}
} while (sum == 100);
Console.WriteLine("Your Score is {0}", score);
Console.WriteLine("GameOver");
}
}
}
for语句
namespace Statement
{
class Program
{
static void Main(string[] args)
{
//for语句内外嵌套循环打印99乘法表
for (int i = 1; i<= 9; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("{0}*{1}={2}\t",i,j,i*j);
}
Console.WriteLine();
}
}
}
}
foreach语句
迭代器原理:
namespace Statement
{
class Program
{
static void Main(string[] args)
{
int[] intarray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
IEnumerator enumerator = intarray.GetEnumerator();//获取int型迭代器
while (enumerator.MoveNext())//MoveNext()方法:返回bool值 若迭代器还能向后移动的话返回true,不能返回false
{
Console.WriteLine(enumerator.Current);//Current表示迭代器指向的当前object
//打印结果为1到8
}
}
}
}
foreach语句示例:
namespace Statement
{
class Program
{
static void Main(string[] args)
{
int[] intarray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
foreach (var i in intarray)
{
Console.WriteLine(i);
}
}
}
}