棄元(Discards) 是在 C# 7.0 的時候開始支援的,它是一種人為丢棄不使用的臨時虛拟變量。文法上它是用來指派的,但它卻不被配置設定存儲空間,即沒有值,是以不能從中讀取值。棄元用 _(下劃線) 表示,下劃線是一個關鍵字,隻能指派,不能讀取,例如:
在 C# 7.0 中,棄元的使用場景主要有下面四種:- 元組和對象的解構
- 使用 is 和 switch 的模式比對
- 對具有 out 參數的方法的調用
- 作用域内獨立使用場景
針對這幾個場景,用下面的幾段代碼示範一下。
場景一:元組/對象的解構
var tuple = (1, 2, 3, 4, 5);
(_, _, _, _, var fifth) = tuple;
場景二:使用 is/switch 的模式比對
var obj = CultureInfo.CurrentCulture.DateTimeFormat;
switch (obj)
{
case IFormatProvider fmt:
Console.WriteLine($"{fmt} object");
break;
case null:
Console.Write("A null object reference");
break;
case object _:
Console.WriteLine("Some object type without format information");
break;
}
if (obj is object _)
{
...
}
場景三:對具有 out 參數的方法的調用
var point = new Point(10, 10);
// 隻要 x, 不關心 y
point.GetCoordinates(out int x, out _);
場景四:作用域内獨立使用場景
void Test(Dto dto)
{
_ = dto ?? throw new ArgumentNullException(nameof(dto));
}
了解了棄元,也了解了棄元的四種使用場景,那麼對下面這個 C# 9.0 新支援的棄元使用場景就容易了解了。
// C# 9 之前
Func<int, int, int> zero = (a, b) => 0;
Func<int, int, int> func = delegate (int a, int b) { return 0; };
// C# 9
Func<int, int, int> zero = (_, _) => 0;
Func<int, int, int> func = delegate (int _, int _) { return 0; };
[Discards - C# Guide] http://dwz.date/bpuV