13.0 表达式的定义
    P13-16 表达式,语句详解 - 图1
    什么是表达式

    • 广义定义:An expressions is a syntactic entity whose evaluation either produces a value or fails to terminate, in which case the expression is undefined.
    • C#对表达式定义:…that can be evaluated to a single value, object, method, or namespace.

      • single value

        1. int x = 100;
        2. x++;
        3. ++x;
      • object

        1. new Form() //new是操作符,form是操作数,括号()用于调用构造函数
        2. (new Form()).ShowDialog();
      • method

        1. Console.WriteLine //“.”是操作符,console和writeline是操作数,得到的结果属于method
        2. Action myActino = new Action(Console.WriteLine); //函数指针
      • namespace

        1. System.Windows.Forms //名称空间访问表达式
        2. System.Windows.Forms.Form myForm = new Form();
    • …expressions can consist of a literal value, a method invocation, an operator and its operands, or a simple name.

      • literal value

        1. int x;
        2. x = 100;
        3. string name;
        4. name = "hello";
      • method invocation

        1. double x = Math.Pow(2, 3);
      • operator and its operands

      • simple name
        1. int x = 100;
        2. int y;
        3. y = x; //"x" is the name of a variable
        13.1 各类表达式概览
        P13-16 表达式,语句详解 - 图2
        C# 语言中表达式的分类(表达式的返回值)
    • A value. Every value has an associated type

      • 表达式产生的这个值的数据类型,也被称作表达式的数据类型
      • 回顾上一节讲的操作符,并回忆由这些操作符组成的表达式所返回的类型
    • A variable. Every variable has an associated type

      1. int x = 100;
      2. int y;
      3. y = x;
    • a namespace

      1. System.Windows.Forms.Form myForm = new Form();
    • a type

      1. var t = typeof(Int32);
    • a method group

      • Console.WriteLine,这是一组方法(19 种重载),重载决策决定具体调用那种方法
    • A null literal

      • null 也是一个值
        1. Form myForm = null;
    • an anonymous function

    • A property access 属性访问

      1. Form myForm = new Form();
      2. myForm.Text = "Hello";
    • An event access 访问某个对象的事件

    • An indexer access 访问索引器
    • Nothing.对返回值为 void 方法的调用

    复合表达式的求值

    • C#语言定义文档里面未明确定义复合表达式,但确实常用
    • 注意操作符的优先级和同优先级操作符的运算方向(除了赋值操作符,基本都是从左向右)

    参考C#语言定义文档

    • 第七章专门讲表达式
    • 对于初学者,仅作参考,不必深究 —— 毕竟我们是在学习语言、不是去实现这门语言

    14.0 语句的定义

    • 广义的定义

    P13-16 表达式,语句详解 - 图3

    P13-16 表达式,语句详解 - 图4

    14.1 语句详解
    P13-16 表达式,语句详解 - 图5

    • embedded-statement 嵌入式语句

    P13-16 表达式,语句详解 - 图6

    声明语句(C#语言定义文档8.5)(c#在线文档)(c#在线文档2)

    • 局部变量声明
    • 局部常量声明

      1. const int x = 100; //常量必须在声明的同时赋值

      表达式语句 expression-statement
      P13-16 表达式,语句详解 - 图7

    • expression-statement 用于计算所给定的表达式。由此表达式计算出来的值(如果有)被丢弃 ```csharp static void Main(string[] args) { // Add 产生的 7.0,如果前面没有拿变量接收它,值被丢弃了 Add(3.0, 4.0); }

    static double Add(double a,double b) { return a + b; }

    1. - Single Responsibility 单一职责原则:一个方法尽量只做一件事情
    2. 下面 `x+y` 这种语句在 C 语言里面是允许的,在 C# 里面不允许
    3. ```csharp
    4. int x = 100;
    5. int y = 200;
    6. x+y; //这里会报错

    块语句
    P13-16 表达式,语句详解 - 图8

    • 块语句无论什么时候都被编译器当做一条语句来看待
    • 编译器认为块语句是一条完整的语句(即块语句最后不用加;号)

      1. namespace OperatorsExample
      2. // 这对括号是名称空间的名称空间体
      3. {
      4. class Program
      5. // 这对括号是program类的类体
      6. {
      7. static void Main(string[] args)
      8. // 这对括号是main方法的方法体
      9. {
      10. // 方法体里的括号是块语句
      11. {
      12. int x = 100;
      13. }
      14. }
      15. }
      16. }
    • 标签语句

      1. hello: Console.WriteLine("hello");
      2. goto hello;
    • 变量的作用域:块之内声明的变量,作用域仅在块内

      1. static void Main(string[] args)
      2. {
      3. int x = 100;
      4. {
      5. Console.WriteLine(x);
      6. int y = 200; //变量y作用域仅在这个块语句内
      7. Console.WriteLine(y);
      8. }
      9. // Error CS0103 当前上下文中不存在名称“y”
      10. Console.WriteLine(y);
      11. }

      选择(判断、分支)语句
      P13-16 表达式,语句详解 - 图9

    • if 语句

      • 编程规范推荐即使只有一条语句,也建议使用块语句
      • 程序员经常修缮前人代码以满足新需求,但因为需求变化(需要实现新逻辑) + 业务逻辑复杂(不敢修改旧代码),导致写出来的代码很臃肿,还很容易陷入思维定式
      • 无论多长的 if else,它都是一条语句。之所以能有 else if{} 这种结构,也是因为 if{} 是一条语句

    P13-16 表达式,语句详解 - 图10

    • switch 语句

    P13-16 表达式,语句详解 - 图11

    image.png

    1. int score = 101;
    2. switch (score / 10)
    3. {
    4. case 10:
    5. if (score == 100)
    6. {
    7. goto case 8;
    8. }
    9. else
    10. {
    11. goto default;
    12. }
    13. // 只有单独的标签才能连起来写。
    14. case 8:
    15. case 9:
    16. // 一旦有了具体的 section,就必需配套 break。
    17. Console.WriteLine("A");
    18. break;
    19. //...后面以此类推
    20. default:
    21. Console.WriteLine("error");
    22. break;
    23. }

    try 语句
    P13-16 表达式,语句详解 - 图13

    • 可以通过 MSDN 查方法相应的异常
      • 如 Int32.Parse 方法 (String) 就有以下异常

    P13-16 表达式,语句详解 - 图14

    • 通用处理异常示例

      1. class Program
      2. {
      3. static void Main(string[] args)
      4. {
      5. Calculator c = new Calculator();
      6. int r = c.Add("abc", "200");
      7. Console.WriteLine(r);
      8. }
      9. }
      10. class Calculator
      11. {
      12. public int Add(string arg1, string arg2)
      13. {
      14. int a = 0;
      15. int b = 0;
      16. try
      17. {
      18. a = int.Parse(arg1);
      19. b = int.Parse(arg2);
      20. }
      21. catch
      22. {
      23. Console.WriteLine("error");
      24. }
      25. int result = a + b;
      26. return result;
      27. }
      28. }
      • 捕捉特定异常

        1. catch (ArgumentNullException)
        2. {
        3. Console.WriteLine("your argument(s) are null");
        4. }
      • 另一种写法(在异常后面加上标识符)

        1. catch (ArgumentNullException ane) //ane是个变量
        2. {
        3. Console.WriteLine(ane.Message);
        4. }

        image.png

    • finally 子句

      • 应该把释放系统资源的语句写在 finally block 里面
      • 有时候也在 finally block 里面写 log
    • throw 子句

      • throw 将异常抛给调用者
      • throw 关键字的语法比较灵活
        1. catch(OverflowException)
        2. {
        3. throw;
        4. }
        迭代(循环)语句 (添加了4个微软C#文档链接)
    • while 语句按不同条件执行一个嵌入语句零次或多次

    • image.png

      • while 语句示例

        1. int score = 0;
        2. bool canContinue = true;
        3. while (canContinue)
        4. {
        5. Console.WriteLine("please input first number");
        6. string str1 = Console.ReadLine();
        7. int x = int.Parse(str1);
        8. Console.WriteLine("please input second number");
        9. string str2 = Console.ReadLine();
        10. int y = int.Parse(str2);
        11. int sum = x + y;
        12. if (sum == 100)
        13. {
        14. score++;
        15. Console.WriteLine("correct {0}+{1}={2}", x, y, sum);
        16. }
        17. else
        18. {
        19. Console.WriteLine("error {0}+{1}={2}", x, y, sum);
        20. canContinue = false;
        21. }
        22. }
        23. Console.WriteLine("your scor is {0}", score);
        24. Console.WriteLine("game over");
    • do 语句按不同条件执行一个嵌入语句一次或多次

    • image.png
    • for 语句计算一个初始化表达式序列,然后,当某个条件为真时,重复执行相关的嵌入语句并计算一个迭代表达式序列
      • for 循环圆括号里面的的三部分都是 opt 可选的(两个分号不能省略),由此可以组成许多平时用不到的奇葩结构
    • image.png

      • 示例1:打印十次hello

        1. for (int counter = 0; counter < 10; counter++)
        2. {
        3. Console.WriteLine("hello");
        4. }
      • 示例2:99乘法表

        1. for (int a = 1; a <= 9; a++)
        2. {
        3. for (int b = 1; b <= a; b++)
        4. {
        5. Console.Write("{0}x{1}={2}\t",a,b,a*b);
        6. }
        7. Console.WriteLine();
        8. }
    • foreach 语句用于枚举一个集合的元素,并对该集合中的每个元素执行一次相关的嵌入语句

    • 遍历和迭代器
      • Array 实现了 IEnumerable

    P13-16 表达式,语句详解 - 图19
    P13-16 表达式,语句详解 - 图20
    P13-16 表达式,语句详解 - 图21

    • 集合遍历的底层原理和迭代器,foreach 语句就是对集合遍历的简记法

      • 迭代器示例

        1. static void Main(string[] args)
        2. {
        3. var intArray = new int[] { 1, 3, 5 ,7};
        4. IEnumerator enumerator = intArray.GetEnumerator();
        5. while (enumerator.MoveNext())
        6. {
        7. Console.WriteLine(enumerator.Current);
        8. }
        9. var intList = new List<int>() { 2, 4, 6, 8 };
        10. IEnumerator enumerator2 = intList.GetEnumerator();
        11. while (enumerator2.MoveNext())
        12. {
        13. Console.WriteLine(enumerator2.Current);
        14. }
        15. }
      • foreach 语句示例

        1. List<int> intList = new List<int>() { 1, 2, 3, 4, 5, 6 };
        2. foreach (var current in intList)
        3. {
        4. Console.WriteLine(current);
        5. }

    跳转语句

    • continue 语句将开始直接封闭它的 while、do、for 或 foreach 语句的一次新迭代
      • continue 语句将终止当前语句的循环,开始一次新的循环
    • break 语句将退出直接封闭它的 switch、while、do、for 或 foreach 语句

      • break 语句直接结束本次循环
        1. if (str1.ToLower()=="end")
        2. {
        3. break;
        4. }
    • goto 语句将控制转到由标签标记的语句

      • goto 语句基本被淘汰
    • throw 语句将引发一个异常
      • throw 语句语法比较灵活,它后面可以什么都不跟
    • return 语句会将控制返回到出现 return 语句的函数的当前调用方

      • 提前 return 原则

        • 通过提前 return 可以让代码阅读者立刻就鉴别出来程序将在什么情况下 return,同时减少 if else 嵌套,写出更优雅的代码
          1. class Program
          2. {
          3. static void Main(string[] args)
          4. {
          5. Greeting("Mr.okay");
          6. }
          7. static void Greeting(string name)
          8. {
          9. if (string.IsNullOrEmpty(name))
          10. {
          11. // 通过尽早 return 可以让代码阅读者立刻就鉴别出来
          12. // name 参数在什么情况下是有问题的
          13. return;
          14. }
          15. Console.WriteLine("Hello, {0}!", name);
          16. }
          17. }
      • 方法的每个分支里面都需要有 return

        • 必须要保证方法的每个分支一定能够return

    未来会讲到的语句

    • using 语句
    • yield 语句
    • lock 语句