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

目录

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!");
                else
                    Console.WriteLine("Good!");
            else
                Console.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,类型为Books
            Books 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,其他->error
            int 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语句
            //调用Calculator
            Calculator 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语句进行改进和continue
            int 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);
            }
            //泛型的list
            List<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注意的事情
            //尽早return
            Greeting("Mr.ok");
            //方法返回值不是void类型,而且在方法使用选择语句,
            //保证选择语句当中,每个方法都能return
            //返回Tim
            var result = WhoisWho("Mr.OK");
            Console.WriteLine(result);
            //返回I don't know
            var 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";
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值