目录

1、表达式语句的定义

2、块语句

3、if语句根据布尔表达式的值选择要执行的语句

4、switch语句

5、try语句

6、迭代语句重复执行嵌入语句、while语句、do语句、for语句、foreach语句

7、continue语句将开始直接封闭它的while、do、for或者foreach语句的一次新迭代


1、表达式语句的定义

语句是高级语言的语法---编译语言和机器语言只有指令(高级语言中的表达式对应低级语言中的指令),语句等价于一个或一组有明显逻辑关联的指令。

高级语言的程序是由语句组成的

低级语言的程序是由指令组成的

C#语言的语句除了能够让程序员顺序的表达算法思想,还能通过条件判断,跳转和循环等方法控制程序逻辑走向。

简言之就是:陈述算法思想,控制逻辑走向,完成有意义的动作。

C#语言的语句由分号(;)结尾,但由分号结尾的不一定都是语句

语句一定是出现在方法体里;

using System;
namespace 表达式2
{class Program{static void Main(string[] args){double result = MyVlaues(2, 7);Console.WriteLine(result);string input = Console.ReadLine();try{double scroe = double.Parse(input);if (scroe >= 60){Console.WriteLine("Pass");}else{Console.WriteLine("Filed!");}}catch (Exception){Console.WriteLine(value: "Not a Number");}//嵌入式语句if (5 > 3)Console.WriteLine("Hello World!");int score = 85;if (score >= 90)if (score >= 80)Console.WriteLine("Best!");elseConsole.WriteLine("Good!");elseConsole.WriteLine("Failed!");//var类型获取到数值之后就不能在改变var x = 100;//更改错误//x=1.32f;Console.WriteLine(x.GetType().FullName);//初始化数组int[] MyArray = { 1, 2, 3, 4, 5, 6, };Console.WriteLine(MyArray[5]);//初始化常量,必须跟上初始化器const int y = 200;Console.WriteLine(y);//表达式语句Console.WriteLine("Hello World!");//对象操作表达式//new Form();//int x2;//x2 = 100;//赋值语句int x2;x2 = 100;x2++;x2--;++x2;--x2;//调用方法需要有变量来接收//double r = Add(50.0,50);//Console.WriteLine(r);Add(7.0, 5.0);//比较字符串string str1 = "This is test!";string str2 = "This is text!";if (string.Compare(str1, str2) == 0){Console.WriteLine(str1 + "and" + str2 + "are equal.");}else{Console.WriteLine(str1 + "and" + str2 + "are  not equal.");}//获取子字符串String str3 = "Last night I dreamt of San Pedro!";Console.WriteLine(str3);String substr = str3.Substring(23);Console.WriteLine(substr);//连接字符串string[] straay = new string[]{"Down the way nights are dark","And the sun shines daily on the mountain top","I took a trip on a sailing ship","And when I reached Jamaica","I made a stop"};string str4 = string.Join("\n",straay);Console.WriteLine(str4);//结构的用法Books book1;  //声明book1,类型为BooksBooks book2;//book1详细信息book1.title = "C programming";book1.author = "nuha ali";book1.subject = "C Programming Tutorial";book1.book_id = 65535;//book2详细信息book2.title = "C Programming";book2.author = "Nuha Ali";book2.subject = "C Programming Tutorial";book2.book_id = 65536;//打印book1信息Console.WriteLine("Book 1 title : {0}", book1.title);Console.WriteLine("Book 1 author : {0}", book1.author);Console.WriteLine("Book 1 subject : {0}", book1.subject);Console.WriteLine("Book 1 book_id :{0}", book1.book_id);//打印book2信息Console.WriteLine("Book 2 title : {0}", book2.title);Console.WriteLine("Book 2 author : {0}", book2.author);Console.WriteLine("Book 2 subject : {0}", book2.subject);Console.WriteLine("Book 2 book_id : {0}", book2.book_id);Console.ReadKey();}static double MyVlaues(double r, double h){double area = 3.1415926 * r * r;double volume = area * h;return volume;}static double Add(double a, double b){//一个方法尽量只做一件事情double result = a + b;Console.WriteLine("Result:{0}", result);return result;}}class Student{public string Name(){return "Hello!";}}/// <summary>/// 结构/// </summary>struct Books{public string title;public string author;public string subject;public int book_id;}
}

2、块语句

block:{}用于只允许使用单个语句的上下文中编写多条语句

block由一个扩在大括号内的可选statement-list组成,如果没有此语句,则称块是空的

块可以包含声明语句,在一个块中声明的局部变量或常量的范围就是该块本身。

在块内,在表达式上下文中使用的名称的含义必须始终相同

块按照以下规则执行:

如果块是空的,控制转到块的结束点,

如果块不是空的,控制转到语句列表,当控制到达语句列表的结束点时,控制转到块的结束点。

如果块本身是可到达的,则块的语句列表是可到达的,

如果块是空的或者如果语句列表的结束点是可到达的,则块的结束点是可到达的。

包含一条或者多条yield语句的block称为迭代器块,迭代器块用于以迭代器的形式实现函数成员。某些附加限制适用于迭代器块

迭代器块中出现return语句时,会产生编译错误(但允许yield return语句)。

迭代器块包含不安全的上下文时将导致编译错误,迭代器块总是定义安全的上下文,即使其定义嵌套在不安全的上下文中也如此。

3、if语句根据布尔表达式的值选择要执行的语句

If-statement:

If(boolean-expression)   embedded-statement

If(boolean-expression)   embedded-statement else embedded-statement

if语句按照以下规则执行:计算boolean-expression

如果布尔表达式产生true,则控制转到第一个嵌入式语句,当如果控制到达那条语句的结束点时,控制将转到if语句的结束点。

4、switch语句

switch语句的主导类型由switch表达式确定

如果switch表达式的类型为Sbyte,byte,short,ushort,int,uint,long,ulong,bool,char,string或者enum-type,或者是对应于以上某种类型的可以为null类型,则该类型就是switch语句的主导类型。

5、try语句

try语句提供一种机制,用于捕捉在块的执行期间发生的各种异常,此外try语句还可以让您指定一个代码块,并保证当控制离开try语句时,总是先执行该代码。

有三种可能的try语句形式

一个try块后接一个或多个catch块、一个try块后接一个finally块

一个try块后接一个或多个catch块,后面再跟一个finally块。

当catch子句指定时,该类型必须为system.exception、从system.exception派生的类型

或者以system.exception或其子类作为有效基类的类型参数类型。

using System;
namespace 表达式3
{class Program{static void Main(string[] args){System.Console.OutputEncoding = System.Text.Encoding.UTF8;//int x = 100;一条块语句//{//    int x = 100;//    if (x > 80) Console.WriteLine(x);//    //标签语句//hello: Console.WriteLine("Hello World!");//goto hello;//    //变量的作用率//    Console.WriteLine(x);//    int y = 200;//    Console.WriteLine(y);             //}//if语句//int x = 200;//int y = 100;//if (x > y)//    if (x == 200)//        Console.WriteLine("hello ");//    if(x!=200)//Console.WriteLine("world!");//if语句+嵌入式语句//int x = 200;//int y = 100;//if (x > y)//{//    Console.WriteLine("Hello");//    Console.WriteLine("World!");//}//带有else的语句//int x1 = 200;//int y1 = 100;//if (x1 > y1)//{//    Console.WriteLine("Hello");//    Console.WriteLine("Yes");//}//else//{//    Console.WriteLine("World!");//    Console.WriteLine("No");//}int score = 95;if (score>=0&&score<=100){if (score>=60){Console.WriteLine("Pass");}//if (score>=0&&score<=59)//{//    Console.WriteLine("Failed");//}//代码重构else{Console.WriteLine("Failed");}                }else{Console.WriteLine("input error!");}int score1 = 79;if (score1>=0&&score1<=100){if (score1>=60){if (score1>=80){Console.WriteLine("A");}else{Console.WriteLine("B");}}else{if (score1>=40){Console.WriteLine("C");}else{Console.WriteLine("D");}}}else{Console.WriteLine("Input error");}//采用新方法实现  else if 语句的的实现int score2 = 79;if (score2>=80&&score2<=100){Console.WriteLine("A");}else if (score2 >= 60){Console.WriteLine("B");}else if (score2 >= 40){Console.WriteLine("C");}else if (score2 >= 0){Console.WriteLine("D");}else{Console.WriteLine("Input error");}//switch语句实现分段//需求80-100->A,60-79->B,40-59->C,0-39->D,其他->errorint score3 = 889;switch (score3/10){case 10:if (score3==100){goto case 8;}else{goto default;}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;}//使用switch进行枚举Level myLEVEL = Level.High;switch (myLEVEL){case Level.High:Console.WriteLine("High");break;case Level.Mid:Console.WriteLine("Mid");break;case Level.Low:Console.WriteLine("Low");break;default:break;}//try语句//调用CalculatorCalculator c = new Calculator();int r = c.Add( "2000" , "200");Console.WriteLine(r);//DivNumber类定义方法除以0时抛出异常DivNumbers d = new DivNumbers();d.division(25, 2);Console.WriteLine();//可空数据类型int? num1 = null;int? num2 = 45;double? num3 = new double?();double? num4 = 3.14157;bool? boolval = new bool?();//显示值Console.WriteLine("显示可空类型的值:{0},{1},{2},{3}",num1,num2,num3,num4);Console.WriteLine("一个可空的布尔值:{0}",boolval);Console.WriteLine();//如果第一个操作数的值为空,则返回第二个操作数的值,否则返回第一个操作数的值。double? numb1 = null;double? numb2 = 3.154;double numb3;numb3 = numb1 ?? 5.34;Console.WriteLine("numb3的值是:{0}",numb3);numb3 = numb2 ?? 5.34;Console.WriteLine("numb3的值是:{0}",numb3);Console.ReadKey();}}enum Level{High,Mid,Low}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(ane.Message);//显示出错具体信息hasError = true;// Console.WriteLine("Your argument(s) are null!");}catch (FormatException fe)//非数字提示{Console.WriteLine(fe.Message);hasError = true;//  Console.WriteLine("Your argument(s) are not number!");}catch (OverflowException oe)//数字值溢出提示{Console.WriteLine(oe.Message);hasError = true;//  Console.WriteLine("Out of range!");}//finally{if (hasError){Console.WriteLine("execution has error");}else{Console.WriteLine("Done");}}int result = a + b;return result;}}/// <summary>/// 除以0时抛出异常/// </summary>public class DivNumbers{int result;public DivNumbers(){result = 0;}public void division(int num1, int num2){try{result = num1 / num2;}catch (DivideByZeroException e){Console.WriteLine("Exception caught: {0}", e);}finally{Console.WriteLine("Result: {0}", result);}}}
}

6、迭代语句重复执行嵌入语句、while语句、do语句、for语句、foreach语句

while语句按照不同条件执行一个嵌入语句零次或多次

while语句按照如下规则执行语句:

计算boolean-expression

如果布尔表达式产生true,控制将转到嵌入语句,当(如果)控制到达嵌入语句的结束点(可能是通过执行一个continue语句时),控制将转到while语句的开头。

如果布尔表达式产生了false,控制将转到while语句的结束点。

在while语句嵌入语句内,break语句可用于将控制转到while语句的结束点(从而结束嵌入语句的迭代),而continue语句可用于将控制转到嵌入语句的结束点(从而执行while语句的另一次迭代)。

如果while语句是可到达的且布尔表达式不具有常量值false,则while语句的嵌入语句是可到达的,如果下列条件中至少有一个为真,则while语句的结束点是可到达的。

do语句

do语句按照不同条件执行一个嵌入语句一次或多次

do、语句包含一个可到达的break语句(它用于退出do语句)

嵌入语句的结束点是可到达的且布尔表达式不具有常量值true。

for语句

for语句计算一个初始化表达式序列,然后,当某个条件为真时,重复执行相关的嵌入语句并计算一个迭代表达式序列

for(for-initializer;for-condition;for-iterator)embedded-statement

foreach语句

用于枚举一个集合的元素,并对该集合中的每个元素执行一次相关的嵌入语句

foreach语句的编译时处理首先确定表达式的集合类型(collection type)、枚举器类型(enumerator type)和元素类型(element type)

此确定按如下过程进行:

如果expression的类型x是数组类型,则存在从x到IEnumerable接口(因为system.array实现此接口)的隐式引用转换,集合类型为IEnumerable接口,枚举器类型为IEnumerator接口,而元素类型以数组类型x的元素类型。

跳转语句

7、continue语句将开始直接封闭它的while、do、for或者foreach语句的一次新迭代

continue语句的目标是直接封闭它的while、do、for或foreach语句的嵌入语句的结束点。如果continue语句不是由while、do、for或foreach语句封闭的,则会发生编译错误。

当多个循环语句嵌套使用时,continue语句将只应用于最里层的那个语句,若要穿越多个嵌套层转义控制,必须使用goto语句。

continue语句按如下规则执行:

  • 如果continue语句要退出的是一个或多个具有关联的finally块的try块,则控制最初将转到最里层的try语句的finally块,当如果控制到达该finally块的结束点时,控制就转到下一个封闭try语句的finally块,此过程不断重复,直到执行完所有涉及的try语句的finally块
  • 控制转到continue语句的目标

由于continue语句无条件的将控制转移到别处,因此永远无法到达continue语句的结束点

using System;
namespace 表达式4
{class Program{static void Main(string[] args){/*//使用while语句练习一个加法小游戏,//和为100加一分,不为100直接退出循环int score = 0;bool canContinue = true;while (canContinue){Console.WriteLine("Please input first number:");string str1 = Console.ReadLine();int x = int.Parse(str1);Console.WriteLine("Please input second numbe:");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...while来实现//int score1 = 0;//int sum = 0;//do//{//    Console.WriteLine("Please input first number:");//    string str1 = Console.ReadLine();//    int x = int.Parse(str1);//    Console.WriteLine("Please input second numbe:");//    string str2 = Console.ReadLine();//    int y = int.Parse(str2);//    sum = x + y;//    if (sum == 100)//    {//        score1++;//        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}.", score1);//Console.WriteLine("Game Over!");/*//使用try语句进行改进和continueint score1 = 0;int sum = 0;do{Console.WriteLine("Please input first number:");string str1 = Console.ReadLine();if (str1.ToLower()=="end"){break;}int x = 0;try{x = int.Parse(str1);}catch {Console.WriteLine("First number has problem,Restart.");continue;}Console.WriteLine("Please input second numbe:");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){score1++;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}.", score1);Console.WriteLine("Game Over!");*///while语句打印十次Hello World/*int counter = 0;while (counter<10){Console.WriteLine("Hello World!");counter++;}Console.WriteLine("******************");//do...while打印int counter1 = 0;do{Console.WriteLine("Hello World!");counter1++;} while (counter1<10);Console.WriteLine("*****************");*///for语句打印十次Hello World/*for (int counter2 = 0; counter2 < 10; counter2++){Console.WriteLine("Hello World!");}*//*//打印乘法表双循环for (int i = 1; i < 9; i++){for (int j = 1; j < i; j++){Console.Write("{0}*{1}={2}\t",j,i,i*j);}Console.WriteLine();}*///什么样的可以被遍历/*int[] MyArray = new int[] { 1,2,3,4,5,6,7,8,};//Console.WriteLine(MyArray.GetType().FullName);//Console.WriteLine(MyArray is Array);IEnumerator enumerator = MyArray.GetEnumerator();//指月//迭代器while (enumerator.MoveNext()){Console.WriteLine(enumerator.Current);}//重新拨回到原来的地方enumerator.Reset();while (enumerator.MoveNext()){Console.WriteLine(enumerator.Current);}//泛型的listList<int> intlist = new List<int>() {1,2,3,4,5, }; IEnumerator enumerator1 = intlist.GetEnumerator();//指月//迭代器while (enumerator1.MoveNext()){Console.WriteLine(enumerator1.Current);}//重新拨回到原来的地方enumerator1.Reset();while (enumerator1.MoveNext()){Console.WriteLine(enumerator1.Current);}*///foreach语句List<int> intlist1 = new List<int>() { 1, 2, 3, 4, 5, 6,7,8,9};foreach (var i in intlist1){Console.WriteLine(i);}//使用return注意的事情//尽早returnGreeting("Mr.ok");//方法返回值不是void类型,而且在方法使用选择语句,//保证选择语句当中,每个方法都能return//返回Timvar result = WhoisWho("Mr.OK");Console.WriteLine(result);//返回I don't knowvar result1 = WhoisWho("Mr.OK1");Console.WriteLine(result1);Console.ReadKey();  }static void Greeting(string name){if (string.IsNullOrEmpty(name)){return;}Console.WriteLine("Hello,{0}", name);}static string WhoisWho(string alias){if (alias=="Mr.OK"){return "Tim";}else{return "I don 't Konw";}}}
}

C#学习记录(四)表达式及if、switch、try、while相关推荐

  1. leveldb 学习记录(四)Log文件

    前文记录 leveldb 学习记录(一) skiplist leveldb 学习记录(二) Slice leveldb 学习记录(三) MemTable 与 Immutable Memtable le ...

  2. MySQL学习记录 (四) ----- SQL数据管理语句(DML)

    相关文章: <MySQL学习记录 (一) ----- 有关数据库的基本概念和MySQL常用命令> <MySQL学习记录 (二) ----- SQL数据查询语句(DQL)> &l ...

  3. Kafka学习记录(四)——消费者

    Kafka学习记录(四)--消费者 目录 Kafka学习记录(四)--消费者 对应课程 Kafka消费者工作流程 消费方式和流程 消费者组原理 消费者组初始化流程 消费者组详细消费流程 重要参数 ka ...

  4. 《你好,放大器》----学习记录(四)

    4 使用放大器的共性问题 4.1 放大器的封装 选择运放的封装,对整体电路板尺寸.焊接工艺和散热有影响,对电路性能也有影响 4.1.1 关于封装的一些基本概念 关于封装,主要关心两个参数: 管脚间距 ...

  5. 【故障诊断发展学习记录四——数字孪生与控制系统健康管理(DT PHM)】

    数字数字 目录 1. 数字孪生的起源 1.1 数字工程 1.2  模型贯穿决策 1.3 数字工程路线图 1.4 数字工程战略目标 2. 美军数字工程 2.1 生态系统全视图 2.2 支持采办的的完整视 ...

  6. python3.10官方文档学习记录四__赋值、比较运算

    1 先来个例子: Python 还可以完成比二加二更复杂的任务. 例如,可以编写 斐波那契数列 的初始子序列,如下所示: >>> # 斐波那契级数: ... # 两个元素的和定义了下 ...

  7. gRPC学习记录(四)--官方Demo

    了解proto3后,接下来看官方Demo作为训练,这里建议看一遍之后自己动手搭建出来,一方面巩固之前的知识,一方面是对整个流程更加熟悉. 官方Demo地址: https://github.com/gr ...

  8. grpc简单使用 java_gRPC学习记录(四)-官方Demo - Java 技术驿站-Java 技术驿站

    了解proto3后,接下来看官方Demo作为训练,这里建议看一遍之后自己动手搭建出来,一方面巩固之前的知识,一方面是对整个流程更加熟悉. 官方Demo地址: https://github.com/gr ...

  9. Python学习记录——이십 lambda表达式

    应用场景 lambda用于简化代码 如果一个函数有一个返回值,并且只有一句代码,可以使用lambda简化 lambda 参数列表: 表达式 lambda的参数列表可有可无,函数的参数在lambda表达 ...

  10. 用python画糖葫芦_python学习记录四

    切片 取一个list或者tuole得部分元素都是非常常见得操作 比如说一个list如下: >>> L = ['Michael','Sarah','Tracy','Bob','Jack ...

最新文章

  1. python画动图-Python绘制动态水球图过程详解
  2. “63个国外优秀测试站点链接”和其他相关资料,排除了目前已失效的网站和资料链接。...
  3. SpringMVC拦截器之拦截器接口方法演示
  4. 《乌合之众》读书笔记(part3)--在群体当中,个人的利益极少会成为强大的动因
  5. taskexecutor_弹簧和线程:TaskExecutor
  6. 如何挑选一款合适的POE工业级交换机?
  7. TCC分布式实现原理及分布式应用如何保证高可用
  8. Windows下,使用dumpcpp 方式访问 COM 接口的方法
  9. 开课吧:人工智能是后互联时代的发展路径和方向
  10. 20180810 突然发现自己不小心跑到了数据分析呈现岗位
  11. 【转】snort 笔记2 ----- 规则编写
  12. Mac idea激活jrebel
  13. 使用百度地图生成器制作疫情小区地图
  14. python opencv 将白色底变成透明底
  15. Android 之自定义表情
  16. 零基础应如何学习UI设计
  17. 旁轴相机,单反相机之间的区别(转)
  18. deepin个性化设置
  19. php for android
  20. Java 3DES加密解密(Commons.Codec Base64)

热门文章

  1. Avada多功能企业主题去授权 WordPress主题模板
  2. 限制对比度自适应直方图均衡化算法原理、实现及效果
  3. 中医(专长)医师证书国家卫计委15号令和卫生部52号令有什么区别
  4. 低代码开发助力家电行业快速搭建售后服务工单管理系统-中易YiTS系统
  5. 移动魔百盒101s刷机注意事项
  6. 图片识别转公式,GitHub 又一 LaTeX 神器面世
  7. 全球及中国坐式充气皮划艇行业产能产量需求及发展前景调研报告2022-2027年
  8. VPI TransmissionMaker光纤通信算法仿真 均衡,载波相位恢复
  9. LTE路测优化工具介绍
  10. 学校学计算机是什么,想学计算机该上什么大学?传智专修学院是个好选择