特殊陳述句
yield陳述句
yield用于終止迭代只能使用在回傳型別必須為 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;
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/120904.html
標籤:C#
上一篇:C#實作將圖片設定成圓形形式顯示
下一篇:C# 索引器(C#學習筆記05)
