zoukankan      html  css  js  c++  java
  • C# yield checked,unchecked lock语句(C#学习笔记04)

    特殊语句

    yield语句

    1. yield用于终止迭代
    2. 只能使用在返回类型必须为 IEnumerable、IEnumerable<T>、IEnumerator 或 IEnumerator<T>的方法、运算符、get访问器中
    using System;
    namespace statement
    {
        class Program
        {
            static System.Collections.Generic.IEnumerable<int> Range(int from, int to)      //yield用法,
            {
                for (int i = from; i < 5; i++)
                {
                    yield return i;
                }
                yield break;
    
                for (int i = 5; i < to; i++)          //在vs2019提示无法访问的语句
                {
                    yield return i;
                }
            }
            static void YieldStatement()
            {
                foreach (int i in Range(-10, 10))
                {
                    Console.WriteLine(i);
                }
            }
            static void Main(string[] args)
            {
                YieldStatement();
            }
        }
    }
    
    

    运行结果:

    -10
    -9
    -8
    -7
    -6
    -5
    -4
    -3
    -2
    -1
    0
    1
    2
    3
    4
    C:Program Filesdotnetdotnet.exe (进程 6072)已退出,返回代码为: 0。
    若要在调试停止时自动关闭控制台,请启用“工具”->“选项”->“调试”->“调试停止时自动关闭控制台”。
    按任意键关闭此窗口...
    

    checked 和 unchecked 语句

    用于控制整型类型算术运算和转换的溢出检查上下文

    static void CheckedUnchecked(string[] args) 
    {
        int x = int.MaxValue;
        unchecked 
        {
            Console.WriteLine(x + 1);  // 溢出,显示错误数据
        }
        checked 
        {
            Console.WriteLine(x + 1);  // 程序调试终止报错
        }     
    }
    

    lock语句

    它的作用是锁定某一代码块,让同一时间只有一个线程访问该代码块

    class Account
    {
        decimal balance;
        private readonly object sync = new object();
        public void Withdraw(decimal amount) 
        {
            lock (sync)                           //同一时间只能有一个线程使用
            {
                if (amount > balance) 
                {
                    throw new Exception(
                        "Insufficient funds");
                }
                balance -= amount;
            }
        }
    }
  • 相关阅读:
    二进制中1的个数
    原码、反码、补码,计算机中负数的表示
    win10安装MySQL
    X86、X64、X86_64
    windows搭建深度学习环境
    驱动
    cpu、gpu
    常见的文件系统
    UltralSO制作U盘启动盘
    save、load
  • 原文地址:https://www.cnblogs.com/asahiLikka/p/11656623.html
Copyright © 2011-2022 走看看