• C#学习 - 表达式、语句


    表达式

    定义

    • 算法逻辑的最基本单元,表达一定的算法意图
    • 是由一个或多个操作数和零个或多个操作符组成的序列
    • 表达式功能是求值,得到的结果可能是一个值、对象、方法或名称空间
    • 因为操作符有优先级,所以表达式也有优先级

    分类

    1. 一个值。表达式返回的任何值都有一个数据类型(所以一般称返回值的类型就是其表达式的类型),任何能得到值的运算
    2. 一个变量。y = x;,x就是一个表达式
    3. 一个名称空间。System.Windows.Forms.Form myForm;
    4. 一个类型。var x = typeof(int32);,int32就是一个表达式
    5. 一个方法组。Console.WriteLine("Hello World");,有两个表达式,第一个是Console.WriteLine,拿到一组方法;第二个是("Hello World"),重载决策决定具体调用哪一个方法
    6. null值表达式。Form myForm = null;
    7. 匿名方法。Action act = delegate() { Console.WriteLine("Hello World") };,赋值符号后面就是一个匿名方法表达式,返回值是一个委托
    8. 属性访问。
    Form myForm = new Form();
    myForm.Text = "Hello World"
    //访问Text属性,是一个表达式
    
    • 1
    • 2
    • 3
    1. 访问某个对象的事件。
    2. 访问索引器。
    List<int> intList = new List<int>() { 1,2,3 };
    int x = intList[1];//访问索引器来访问第n+1个元素
    
    • 1
    • 2
    1. Nothing。对返回值为void的方法的调用,Console.WriteLine("Hello World");,没有返回值

    复合表达式求值

    复合表达式就是由多个表达式串连起来的语句
    注意操作符的优先级和同优先级操作符的运算方向

    语句

    定义

    语句是命令式编程语言中最小的独立元素,语句的功能就是表达一些将被执行的动作。编程就是使用语句编写程序
    只有高级语言才有语句,而低级语言(汇编语言和机器语言)只有指令。高级语言中的表达式对应低级语言中的指令,而语句就是一个或一组有明显逻辑关联的指令
    程序当中语句执行的顺序叫控制流(执行流)
    C#语言中的语句不仅能让程序员“顺序地”(语句的输入顺序)表达算法思想,还能通过条件判断、跳转和循环等方法控制程序的逻辑走向
    语句就是陈述算法思想、控制逻辑走向、完成有意义的动作
    C#中的语句由分号结尾,但由分号结尾的不一定是语句

    using System;//这不是语句,而是using指令
    class Tool
    {
    	public string Knife;//字段的声明,而不是语句
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    语句一定是出现在方法体中的
    C#中有3大类语句:标签语句声明语句嵌入式语句

    if (true)
    {
    	Console.WriteLine("Hello World");//嵌入式语句
    }
    
    • 1
    • 2
    • 3
    • 4

    嵌套在其他语句中的语句就叫做嵌入式语句

    声明语句

    声明语句分为局部变量声明和局部常量声明。

    局部变量声明

    语句构成: 局部变量的数据类型 + 局部变量声明器
    局部变量声明器可以是一个声明器;
    也可以是一组声明器再接一个局部变量声明器,此局部变量声明器可以是一个单独的标识符,也可以是“标识符 = 本地变量初始化器”,本地变量初始化器可以是一个值,也可以是一个数组

    int x, y, z;//一组局部变量声明器接标识符
    int a = 1; b = 2; c = 3;//一组局部变量声明器接“标识符 = 本地变量初始化器”
    
    • 1
    • 2

    局部常量声明

    const int x = 10;//此时x成为了常量
    
    • 1

    常量在声明时就需要跟上初始化器进行初始化

    表达式语句

    语句构成 = 语句表达式 + ;
    即是可以形成语句的表达式
    用于计算所给定的表达式,此表达式如果有所计算出来的值,那个值就会被丢弃

    static void Main(string[] args)
    {
    	Add(1.0, 2.0);//此表达式计算出的3.0会被丢弃掉
    }
    static double Add(double x, double y)
    {
    	return x + y;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    并非所有表达式都能成为语句,不允许像 x + y 和 x == 1这样只计算一个值(此值会被抛弃)的表达式作为语句

    int x = 100; y = 200;
    x + y;//报错,C#中此表达式不是语句
    
    • 1
    • 2

    调用表达式语句

    即调用方法表达式

    Console.WriteLine("42");//方法调用表达式,接上分号就成了一个语句
    
    • 1

    对象创建表达式语句

    即是 new 操作符构成的表达式
    new 操作符会创建一个对象,而且去调用对象的构造器

    new Form();//一个语句,虽然没什么作用
    
    • 1

    赋值语句

    int x;//声明语句
    x = 100;//赋值语句
    
    • 1
    • 2

    前置后置±±

    int a = 0;
    a++;//后置++
    a--;//后置--
    ++a;//前置++
    --a;//前置--
    
    • 1
    • 2
    • 3
    • 4
    • 5

    await表达式

    进行异步编程

    块语句(简称“块”)

    块(block)用于只允许使用单个语句的上下文中编写多条语句
    block由一个扩在大括号内的可选的语句列表组成
    语句列表是由一个或多个顺序编写的语句组成,C#中的语句都能写到块语句中,包含标签语句、声明语句、嵌入式语句

    • 块语句在任何时候都会被编译器当成一条语句
    • 编译器会认为块语句是一条完整的语句,不需要在最后加花括号
    static void Main(string[] args)
    {
    	{
    	hello: Console.WriteLine("Hello World");//标签语句
    		int x = 100;//声明语句
    		if (x > 1)//嵌入式语句
    			Console.WriteLine(x);
    	}//此花括号与其内部就是一个块语句
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    在快语句内能使用在块之外声明的变量,但块语句内声明的变量不能在块之外使用

    选择(判断、分支)语句

    选择语句会根据表达式的值从若干个给定的语句中选择一个来执行

    if 语句

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

    if ( 布尔类型的表达式 )
    	一条嵌入式语句
    //后面均可在不必要时省略
    else if ( 布尔类型的表达式 )//就是else语句中嵌套一个if语句
    	一条嵌入式语句
    //...此处可以一直写else if 
    else
    	一条嵌入式语句
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    不论嵌套多少次,语句有多长,这整个语句都是一个 if 语句
    布尔类型表达式得值为True,执行紧接着的一条嵌入式语句,跳过后面的语句
    嵌入式语句中有一种语句是块语句,所以使用块语句可以在 if 语句中编写多条语句

    if (true)//打印 Hello World
    	Console.WriteLine("Hello World");
    //-----------
    if (false)//打印 Yes
    	Console.WriteLine("C#");
    else 
    	Console.WriteLine("Yes");
    //-----------
    if (true)
    {
    	Console.WriteLine("A");
    	Console.WriteLine("B");
    }//使用了块语句
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    switch 语句

    switch ( 表达式 ) switch块语句
    
    • 1

    switch后的表达式的求值类型必须为 sbyte、byte、short、ushort、int、uint、long、ulong、bool、char、string、可空类型

    int x = 8;
    switch (x)
    {
    case 8://case后的表达式类型需要与 x 的类型一致
    case 9://case后的表达式必须是常量
    case 10://可以多个 case 对应一个语句
    	Console.WriteLine("A");
    	break;//case 中必须要有一个 break
    case 6:
    case 7:
    	Console.WriteLine("B");
    	break;
    case 0:
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    	Console.WriteLine("C");
    	break;
    default://当所有条件都不符合时,跳入default分支中
    	Console.WriteLine("Error");
    	break;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    try 语句

    用于捕捉在块的执行期间发生的各种异常

    • 当块语句中发生异常,可以用catch子句捕捉,catch子句可以有多个
    • catch子句有通用和专用,由catch后的异常类型决定
    • catch子句的异常类型后可以接标识符,可用于自动打印异常原因
    • try语句最后可以接入finally子句,finally子句不论会不会出异常都会执行,finally子句只能最多有一个
    • finally子句一般用于申请一些系统的资源或者是程序的执行记录
    1. 通用型catch
    int a = 0;
    int b = 0;
    try
    {
    	a = int.Parse(arg1);
    	b = int.Parse(arg2);
    }
    catch//通用型的 catch
    {
    	Console.WriteLine("Argument(s) is error");
    }
    Console.WriteLine(a + b);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    1. 专用型catch
    int a = 0;
    int b = 0;
    try
    {
    	a = int.Parse(arg1);
    	b = int.Parse(arg2);
    }
    catch (ArgumentNullException)
    {	//专用型catch子句
    	Console.WriteLine("Argument(s) are null");
    }
    catch (FormatException fe)//fe就是一个标识符
    {	//fe就是一个变量,访问异常的实例
    	Console.WriteLine(fe.Message);//打印出异常原因
    }
    catch (OverflowException oe)
    {
    	Console.WriteLine(oe.Message);
    }
    Console.WriteLine(a + b);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    1. finally子句使用
    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;
    }
    catch (FormatException fe)
    {
    	Console.WriteLine(fe.Message);
    	hasError = true;
    }
    catch (OverflowException oe)
    {
    	Console.WriteLine(oe.Message);
    	hasError = true;
    }
    finally//此处的finally用来打印出执行记录(Log)
    {
    	if (hasError)
    	{
    		Console.WriteLine("Execution has error");
    	}
    	else
    	{
    		Console.WriteLine("Done");
    }
    Console.WriteLine(a + b);
    
    • 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
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    throw关键字

    当只想处理某些异常,而其他异常不想处理,而让其他异常throw出去
    throw出去就是让其他方法调用方法时抓住异常去处理

    internal class Program
    {
    	static void Main(string[] args)
    	{
    		Tool t = new Tool();
    		int x = 0;
    		try
    		{
    			x = t.Add("100", "200");
    		}
    		catch (ArgumentNullException ane)
    		{
    			Console.WriteLine(ane.Message);
    		}
    		Console.WriteLine(x);
    	}
    }
    class Tool
    {
    	public int Add(string arg1, string arg2)
    	{
    		int a = 0;
    		int b = 0;
    		try
    		{
    			a = int.Parse(arg1);
    			b = int.Parse(arg2);
    		}
    		catch (ArgumentNullException ane)
    		{
    			throw ane;//throw关键字比较灵活,后面不需要接标识符
    			//整个catch子句中无标识符也可使用throw
    		}
    		catch (FormatException fe)
    		{
    			Console.WriteLine(fe.Message);
    		}
    		catch (OverflowException oe)
    		{
    			Console.WriteLine(oe.Message);
    		}
    		return a + b;
    	}
    }
    
    • 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
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    迭代语句

    迭代语句可以重复执行嵌入语句

    • while语句
    • do语句
    • for语句
    • foreach语句

    while语句

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

    while (布尔类型的表达式)
    {
    	嵌入式语句;
    }
    
    • 1
    • 2
    • 3
    • 4
    //输入分数,当分数低于60即失败
    int i = 1;
    bool canContiune = true;
    while (contiune)
    {
    	Console.WriteLine("Enter your score {0}:>", i);
    	string score = Console.ReadLine();
    	int x = int.Parse(score);
    	if (x < 60)
    	{
    		canContiune = false;
    	}
    	i++;
    }
    Console.WriteLine("You Lose");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    do语句(do while语句)

    在不同条件的控制下执行嵌入语句一次或者多次
    do语句先执行嵌入语句再判断

    do
    {
    	嵌入式语句;
    } while (布尔类型表达式);
    
    • 1
    • 2
    • 3
    • 4
    int i = 1;
    int x = 0;
    do
    {
    	Console.WriteLine("Enter your score {0}:>", i);
    	string score = Console.ReadLine();
    	x = int.Parse(score);
    	i++;
    } while (x > 60);
    Console.WriteLine("You Lose");
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    for语句

    重复执行相关地嵌入语句并计算一个迭代表达式序列

    for (for循环初始化器; for循环条件; for-iterator)//for-iterator在每次循环后都会执行一次
    //for循环()内地三部分都可以省略,但两个";"必须有
    {
    	嵌入语句;
    }
    //for循环开始时,初始化器最先执行且只执行一次
    //再进行判断是否满足循环条件
    //满足条件执行嵌入语句后再执行for-iterator
    //不满足条件直接结束循环
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    //打印3次Hello World
    for(int i = 0; i < 3; i++)
    {
    	Console.WriteLine("Hello World");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    //打印九九乘法表
    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();
    }
    //打印三角形
    for (int i = 1; i <= 9; i += 2) 
    {
    	for (int j = 1; j <= 5 - (i + 1) / 2; j++)
    	{
    		Console.Write(" ");
    	}
    	for (int k = 1; k <= i; k++)
    	{
    		Console.Write("*");
    	}
    	Console.WriteLine();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    foreach语句

    用于枚举一个集合中地元素(遍历语句),可以对一个集合中的每个元素执行一次嵌入语句

    什么样的集合能被遍历?
    int[] intArray = new int[] { 1, 2, 3, 4 };
    Console.WriteLine(intArray.GetType().FullName);
    //打印System.Int32[]
    
    • 1
    • 2
    • 3

    一个数据类型以方括号结尾就是数组类型,C#中所有数组类型都以Array类作为基类
    Array有以下接口:

    • ICloneable
    • IList
    • ICollection
    • IEnumerable
    • IStructuralComparable
    • IStructuralEquatable
      C#中所有实现了IEnumerable这个接口地类就是能被遍历地集合
      IEnumerable这个接口只有一个GetEnumerator地方法,也就是说C#中所有能够被遍历地集合都能获得自身地迭代器
    迭代器(Enumerator)
    public interface IEnumerator
    {
    	object Current { get; }
    
    	bool MoveNext();
    	void Reset();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • Current:就是当前访问的元素
    • MoveNext:返回值是bool类型,当未到最后一个元素时,都是返回true
    • Reset:把迭代器拨回到集合的最开始
    int[] intArray = new int[] { 1, 2, 3, 4, 5 };
    IEnumerator enumerator = intArray.GetEnumerator();//获得迭代器
    while (enumerator.MoveNext()) 
    {
    	Console.WriteLine(enumerator.Current);
    }
    while (enumerator.MoveNext())
    {
    	Console.WriteLine(enumerator.Current);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    上段代码只会打印一次 1 2 3 4 5 ,第一次打印完时,迭代器已经到了最后,所以需要先进行Reset

    foreach

    foreach语句就是简化版迭代器

    foreach (声明一个迭代变量 in 集合名)
    {
    	嵌入语句;
    }
    
    • 1
    • 2
    • 3
    • 4
    int[] intArray = new int[] { 1, 2, 3, 4, 5 };
    foreach (var i in intArray)
    {
    	Console.WriteLine(i);
    }//打印 1 2 3 4 5
    
    • 1
    • 2
    • 3
    • 4
    • 5

    跳转语句

    跳转语句用于无条件地转移控制

    continue语句

    用于循环语句中,放弃当前循环进行下一次循环(迭代语句)

    int i  = 0;
    while (i < 5)
    {
    	i++;
    	if (i == 3)
    	{
    		continue;
    	}
    	Console.WriteLine(i);
    }
    //输出 1 2 4 5
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    break语句

    用于循环语句中,终止循环语句(迭代语句)

    int i  = 0;
    while (i < 5)
    {
    	i++;
    	if (i == 3)
    	{
    		break;
    	}
    	Console.WriteLine(i);
    }
    //输出 1 2
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    goto语句

    快速跳转到其他语句

    throw语句

    转到:try语句 - throw关键字

    return语句

    在方法体中经常使用。方法返回值为void时,执行到最后一句会自动return
    使用原则:

    • 尽早return
    • 返回值不是void或使用了选择语句,要在选择语句的每一个分支中都有return
  • 相关阅读:
    ABAP Data Types 和XSD Type 映射关系以及XSD Type属性
    py 时候同时打开多个页面,操作多个页面
    CycleGAN模型之Pytorch实战
    【设计模式】设计模式
    LDA主题分析可视化
    大模型从入门到应用——LangChain:代理(Agents)-[代理执行器(Agent Executor):处理解析错误、访问中间步骤和限制最大迭代次数]
    STM32物联网项目-DAC输出模拟量以及正弦波
    AI赋能药物研发的偶然与必然
    elementUI可拖拉宽度抽屉
    微服务探索之路06篇k8s配置文件Yaml部署Redis使用Helm部署MongoDB和kafka
  • 原文地址:https://blog.csdn.net/Pokipata/article/details/133041862