第 13、14、15、16 节 表达式,语句详解

第13、14、15、16节 表达式,语句详解

表达式的定义

  1. 什么是表达式
    1)Expressions, together with commands and declarations, are one of the basic components of every programming language. We can say that expressions are the essential component of every language.(任何语言的核心组件)
    2)An expressions is a syntactic entity (语法实体)whose evaluation either produces a value or fails to terminate, in which case the expression is undefined.(表达式是专门用来求值的语法实体)
    3)各种编程语言对表达式的实现不尽相同,但大体上都符合这个定义。

  2. C# 语言对表达式的定义
    1)An expression is a sequence of one or more operands (至少有一个操作数)and zero or more operators (零或更多操作符)that can be evaluated to a signal value, object, method, or namespace. Expressions can consist of a literal value(字面值), a method invocation(方法调用), an operator(操作符) and its operands(操作数), or a simple name. Simple names can be the name of a variable, type member, method parameter, namespace or type.
    2)算法逻辑的最基本(最小)单元,表达一定的算法意图
    3)因为操作符有优先级,所以表达式也就有了优先级

举例:

// signal value
int x = 100;
x++; ++x;
// object
new Form(); 
//method
Action myAction = new Action(Console.WriteLine); 
// .是成员访问操作符,操作的对象是Console和WriteLine,得到结果是WriteLine方法
//namespace
System.Windows.Forms.Form myForm = new Form();

各类表达式概览

  1. C#语言中表达式的分类
    1)A value. Every value has an associated type(数据类型). 任何能得到值的运算(回顾操作符和结果类型)
    2)A variable. Every variable has an assiociated type.
    3)A namespace.
    4)A type.
    5)A method group. 例如:Console.WriteLine,这是一组方法,重载决策决定具体调用哪一个
    6)A null literal. null不属于任何数据类型
    7)An anonymous function.
    8)An property access.(访问属性)
    9)An event access.(访问事件)
    10)An indexer access.(访问集合成员)
    11)Nothing. 对返回值为void的方法的调用

访问属性和事件

class Program
{
    static void Main(string[] args)
    {
        Form myForm = new Form();
        myForm.Text = "Hello";
        myForm.Load += MyForm_Load;
        myForm.ShowDialog();
    }

    private static void MyForm_Load(object sender, EventArgs e)
    {
        Form form = sender as Form;
        if (form == null)
        {
            return;
        }

        form.Text = "New Title";
    }
}
  1. 复合表达式的求值
    注意操作符的优先级和同优先级操作符的运算方向

  2. 参考 C# 语言定义文档
    仅作参考,不必深究——学习语言而不是实现这门语言

语句的定义

  1. Wikipedia 对语句的定义
    1) In computer programming a statement(命令) is the smallest standalone(独立的) element of an imperative programming language which exprsses some action to be carried out. A program written in such a language is formed by a sequence of one or more statements. A statement will have internal compents (e.g., expressions).
    2)语句是高级语言的语法——编译语言和机器语言只有指令(高级语言中的表达式对应低级语言中的指令),语句等价于一个或一组有明显逻辑关联的指令。举例:求圆柱体积。
    注: 指令是CPU可以直接执行的动作。
  2. C# 语言对语句的定义
    1)The actions that a program takes are expressed in statements. Common actions include declaring variables, assigning values, calling methods, looping through collections, and branching to one or another block of code, depending on a given condition. The order in which statements are executed in a program is called the flow of control or flow of execution. The flow of control may vary every time that a program is run, depending on how the program reacts to input that it receives at run time.
    2)C# 语言的语句除了能够让程序员“顺利地”(sequentially)表达算法思想,还能通过条件判断、跳转和循环等方法控制程序逻辑的走向
    3)简言之就是:陈述算法思想,控制逻辑走向,完成有意义的动作(action)
    4)C#语言的语句由分号(;)结尾,但由分号结尾的不一定都是语句
    using System; //这是一个指令,引入名称空间
    public string Name; //字段的声明,不是语句
    5)语句一定是出现在方法体里

语句详解

语句被分为 3 类,分别是

  1. labeled-statement(标签语句)
    hello: Console.WriteLine("Hello, world!"); //hello是标签,整个句子是标签语句
  2. declaration-statement(声明语句)
    作用:声明变量和常量
  3. embedded-statement (嵌入式语句)
    1)block
    2)empty-statement
    3)selection-statement
    4)iteration-statement
    5)jump-statement
    6)try-statement
    7)checked-statement
    8)unchecked-statement
    9)lock-statement
    10)using-statement
    11)yield-statement


初学者需要熟练使用的语句:声明语句,表达式语句,块语句(简称“块”),选择(判断、分支)语句,迭代(循环)语句,跳转语句,try…catch…finally语句。
需理解记忆的语句:using语句,yield语句,checked/unchecked语句,lock语句(用于多线程),标签语句,空语句。

  1. 声明语句
    1)声明变量
    int x;
    2)声明常量(在声明的同时必须跟上初始化器)
    const int x = 100; //在变量的声明前面加 const
  2. 表达式语句(形式:语句表达式;)
    表达式语句用于计算机所给定的表达式。由此表达式计算出来的值(如果有)被丢弃
    语句表达式:
    1)invocation-expression (调用表达式):
    Console.WriteLine("Hello, world!");
    2)object-creation-expression(对象创建表达式):
    new Form();
    3)assignment(赋值语句)
    int x; //声明语句
    x = 100; //赋值语句
    4)post-increment-expression(后置自增表达式)
    5)post-decrement-expression(后置自减表达式)
    6)pre-increment-expression(前置自增表达式)
    7)pre-decrement-expression(前置自减表达式)
    8)await-expression
    :尽量避免一个方法里面有多个功能,最好是一个方法执行一种功能。
    :不是所有的表达式都允许作为语句使用。具体而言,不允许像 x+y 和 x==1 这样值计算一个值(此值将被放弃)的表达式作为语句使用。C#语言中不可以,但是C语言中可以
  1. 块语句(在方法体中的一条语句,子语句用{ }包含起来)
    块语句用于在只允许使用单个语句的上下文中编写多条语句。
    变量的作用域:在一条块语句之前和之外声明的变量,在块语句里是可以访问的,但是在块语句里面声明的变量,在块之外不能被访问。

visual studio的小技巧:
Ctrl+ } :在开始花括号和结束花括号之间进行跳转

  1. 选择语句(使用代码提示:输入 if,双击 tab)
    1)if 语句
    第一种:
    ifboolean-expression
    {embedded-statement (一条嵌入式语句)}
    第二种:
    ifboolean-expression
    {embedded-statement}
    else
    {embedded-statement }
    2)switch语句
    :标签必须是常量值;每个 selection 必须显示地写上 break;switch 表达式的类型为 sbyte、byte、short、ushort、int、uint、long、ulong、bool、char、string、enum-type(枚举类型) 或者它们对应的 null 的类型。
    举例:
// if 语句
class Program
{
    static void Main(string[] args)
    {
        int score = 100;  //利用边界值进行验证
        if (score < 0 || score > 100)
        {
            Console.WriteLine("Input Error!");
        }
        else if (score >= 80)  //为了让程序的可读性更高,else if一般采用这样的书写格式
        {
            Console.WriteLine("A");
        }
        else if (score >= 60)
        {
            Console.WriteLine("B");
        }
        else if (score >= 40)
        {
            Console.WriteLine("C");
        }
        else if (score >= 0)
        {
            Console.WriteLine("D");
        }
    }
}
// switch 语句
class Program
{
    static void Main(string[] args)
    {
        int score = 101;
        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 4:
            case 5:
                Console.WriteLine("C");
                break;
            case 0:
            case 1:
            case 2:
            case 3:
                Console.WriteLine("D");
                break;
            default:
                Console.WriteLine("Error!");
                break;
        }
    }
}
//switch的表达式是枚举类型
class Program
{
    static void Main(string[] args)
    {
        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;
        }
    }

    enum Level
    {
        High,
        Mid,
        Low
    }
}
  1. try 语句
    try 语句提供一种机制,用于捕捉在块的执行期间发生的各种异常。此外,try 语句还能让您制定一个代码块,并保证当控制离开 try 语句时,总是先执行
    有三种可能的 try 语句形式:
    try block catch-clauses
    try block finally-clause
    try block catch-clauses finally-clause
class Program
{
    static void Main(string[] args)
    {
        Calculator calculator = new Calculator();
        int result = calculator.Add(null, "200");
        Console.WriteLine(result);
    }

    class Calculator
    {
        int a = 0;
        int b = 0;
        public int Add(string arg1, string arg2)
        {
        		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
            {
            		if(hasError)
            		{
            				Console.WriteLine("Execution has error!");
            		}
            		else
            		{
            				Console.WriteLine("Done!");
            		}
            }

            int result = a + b;
            return result;
        }
    }
}

finally 子句:当在执行 try 语句时,无论是否会发生异常,finally 子句都会被执行。一般,在finally 子句里面1)写用于存放释放系统资源的语句,无论是否发生异常都会执行;2)写程序的执行记录。

throw: 将异常抛出,交由调用者来处理。

:尽可能利用 try 语句去处理有可能出现的异常。

  1. 迭代语句(循环语句)和跳转语句
    迭代语句:
    1)while 语句(执行零次或多次)
    while (boolean-expression) embedded-statement ;
    2)do 语句(执行一次或多次)
    do embedded-statement while (boolean-expression);
    3)for 语句
    for 语句计算一个初始化表达式序列,然后,当某个条件为真时,重复执行相关的嵌入语句并计算出一个迭代表达式序列。
    for (for-initializer; for-condition; for-iterator) embedded-statement
    4)foreach 语句
    foreach 语句用于枚举一个集合的元素,并对该集合中的每个元素执行一次相关的嵌入语句。(集合遍历的简记法)
    foreach (local-variable-type identifier in expression) embedded-statement
    跳转语句:
    1)break 语句
    break 语句将退出直接封闭它的 switch、while、do、for 或 foreach 语句。
    2)continue 语句
    continue 语句将开始直接封闭它的 while、do、for 或 foreach语句的一次新迭代
    3)goto 语句
    4)throw 语句
    5)return 语句(尽早 return 原则)

举例:
while 语句

class Program
{
    static void Main(string[] args)
    {
        int score = 0;
        bool canContinue = true;
        while (canContinue)
        {
            Console.WriteLine("Please input the first number:"); //在屏幕上显示
            string str1 = Console.ReadLine(); //键盘输入
            int x = int.Parse(str1);

            Console.WriteLine("Please input the second 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!");
    }
}

使用迭代器迭代集合的方法

class Program
{
    static void Main(string[] args)
    {
        int[] intArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8 };
        List<int> intList = new List<int>() { 1, 2, 3, 4, 5, 6 };

        IEnumerator enumerator = intArray.GetEnumerator();  //指月,获得迭代器
        while (enumerator.MoveNext())
        {
            Console.WriteLine(enumerator.Current);
        }

        enumerator.Reset();

        while (enumerator.MoveNext())
        {
            Console.WriteLine(enumerator.Current);
        }
    }
}

foreach 语句适用于集合的遍历,减少了迭代器的声明等步骤

class Program
{
    static void Main(string[] args)
    {
        List<int> intList = new List<int>() { 1, 2, 3, 4, 5, 6 };

        foreach (var current in intList)
        {
            Console.WriteLine(current);
        }
    }
}

return 语句有尽早 return 原则;要保证每一个有返回值的方法一定能够 return。

class Program
{
    static void Main(string[] args)
    {
        Geetting("Sunine");
    }

    static void Geetting(string name)
    {
        if (string.IsNullOrEmpty(name))
        {
            return; //尽早 return
        }

        Console.WriteLine("Hello, {0}!", name);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值