zoukankan      html  css  js  c++  java
  • 【C#语言规范版本5.0学习】1.4语句

    程序的操作是使用语句 (statement) 来表示的。

    C# 支持几种不同的语句,其中许多以嵌入语句的形式定义。

    block 用于在只允许使用单个语句的上下文中编写多条语句。块由位于一对大括号 { 和 } 之间的语句列表组成。

    声明语句 (declaration statement) 用于声明局部变量和常量。

    表达式语句 (expression statement) 用于对表达式求值。可用作语句的表达式包括方法调用、使用 new 运算符的对象分配、使用 = 和复合赋值运算符的赋值、使用 ++ 和 -- 运算符的增量和减量运算以及 await 表达式。

    选择语句 (selection statement) 用于根据表达式的值从若干个给定的语句中选择一个来执行。这一组中有 if 和 switch 语句。

    迭代语句 (iteration statement) 用于重复执行嵌入语句。这一组中有 while、do、for 和 foreach 语句。

    跳转语句 (jump statement) 用于转移控制。这一组中有 break、continue、goto、throw、return 和 yield 语句。

    try...catch 语句用于捕获在块的执行期间发生的异常,try...finally 语句用于指定终止代码,不管是否发生异常,该代码都始终要执行。

    checked 语句和 unchecked 语句用于控制整型算术运算和转换的溢出检查上下文。

    lock 语句用于获取某个给定对象的互斥锁,执行一个语句,然后释放该锁。

    using 语句用于获得一个资源,执行一个语句,然后释放该资源。

    下表列出了 C# 的各语句,并提供每个语句的示例。

    //goto 语句
    static void Main(string[] args) {
    int i = 0;
    goto check;
    loop:
    Console.WriteLine(args[i++]);
    check:
    if (i < args.Length) goto loop;
    }
    
    //局部常量声明
    static void Main() {
    const float pi = 3.1415927f;
    const int r = 25;
    Console.WriteLine(pi * r * r);
    }
    
    //yield 语句
    static IEnumerable<int> Range(int from, int to) {
    for (int i = from; i < to; i++) {
    yield return i;
    }
    yield break;
    }
    static void Main() {
    foreach (int x in Range(-10,10)) {
    Console.WriteLine(x);
    }
    }
    
    //checked 和unchecked 语句
    static void Main() {
    int i = int.MaxValue;
    checked {
    Console.WriteLine(i + 1); // Exception
    }
    unchecked {
    Console.WriteLine(i + 1); // Overflow
    }
    }
    
    //lock 语句
    class Account
    {
    decimal balance;
    public void Withdraw(decimal amount) {
    lock (this) {
    if (amount > balance) {
    throw new Exception("Insufficient funds");
    }
    balance -= amount;
    }
    }
    }
    
    //using 语句
    static void Main() {
    using (TextWriter w = File.CreateText("test.txt")) {
    w.WriteLine("Line one");
    w.WriteLine("Line two");
    w.WriteLine("Line three");
    }
    }
    View Code
  • 相关阅读:
    20155328 《网络攻防》 实验一:PC平台逆向破解(5)M
    20155328 《信息安全系统设计基础》 课程总结
    构建之法
    20155327 2017-2018-2《Java程序设计》课程总结
    20155327 实验五 网络编程与安全
    20155327 网络对抗 实验
    20155327 Exp9 Web安全基础
    20155327 EXP8 Web基础
    20155327 实验四 Android程序设计
    20155327 李百乾 Exp7 网络欺诈防范
  • 原文地址:https://www.cnblogs.com/TechSingularity/p/14314376.html
Copyright © 2011-2022 走看看