C# yield checked,unchecked lock语句(C#学习笔记04)

2022-10-14,,,,

特殊语句

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 files\dotnet\dotnet.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;
        }
    }
}

《C# yield checked,unchecked lock语句(C#学习笔记04).doc》

下载本文的Word格式文档,以方便收藏与打印。