原文:https://blogs.msdn.microsoft.com/mazhou/2017/06/06/c-7-series-part-3-default-literals/
C#的default關鍵字有兩種用法:一種是標記switch…case結構的默認分支(會匹配任意不被所有case條件匹配的路徑);另一種方法是表示型別的“默認”值,我將在本文中討論這個用法,
一個型別的默認值:
- 如果型別是參考型別,則為空
- 如果型別是值型別,則使用這個值型別的無引數建構式構造出來的實體,
下面的截圖是一個簡單的例子,

但是,你不能對任何開放型別使用默認運算式(注意:開放型別是具有未系結型別引數的型別;一個擁有所有的系結型別引數的型別被稱為封閉型別),例如:

現在,如果我們想在一個方法中使用泛型型別的默認值,我們必須寫類似這樣的代碼:
public static void Method(ImmutableArray<int> array) { } public static void Main(string[] args) { Method(default(ImmutableArray<int>)); }
你看到上面代碼的冗余了嗎?編譯器應該知道Method()所需的第一個引數的確切型別,所以一個不需要具體型別的關鍵字default應該足夠了,
默認文本運算式
C# 7.1允許default運算式,如果使用C#語言版本7.1或更新版本進行編譯,您可以將代碼簡化如下:
public static void Method(ImmutableArray<int> array) { } public static void Main(string[] args) { Method(default); }
現在你的代碼簡潔了!
類似地,你可以在default(…)運算式可以出現的所有地方使用默認文本運算式:
public static void Main(string[] args = default) { // 可選引數的默認值 int i = default; // 型別 System.Int32 的默認值 0 string s = default; // 型別 System.String 的默認值 null Method(default); // 使用引數的默認值呼叫一個方法 T t = default; // 型別引數的默認值 return default; // 一個有回傳值的方法回傳默認值 }
你還能夠在判斷條件中使用默認文本運算式
int x = 2; if (x == default) { } // 判斷x是否是型別 System.Int32 的默認值 0 if (x is default) { } // 同上
更有趣的是,您可以在switch…case陳述句中使用默認文本運算式,哦,太酷了!等一下,要是我輸入"case default"標簽呢?下面這張圖是我在VS中輸入case default的截圖:

如果你使用VS的建議來修改你的陳述句,就會變成下面這樣:
int x = 2; switch (x) { case (default): break; //譯注:VS建議使用case 0 或者 case null來代替, default: break; }
這看起來很讓人困惑,但至少我們得到了關于這個的實時分析,感謝Roslyn!(譯注:C#編譯器)
我想說的最后一件事是,有些情況下不能應用默認文本運算式,例如:
// 錯誤: 'as' 必須用在參考型別 default as int; // OK. 但是左邊的運算式總是null, if (default as string == string.Empty) { } // 錯誤,不能對default關鍵字使用運算子is, if (default is string) { }
結論
C# 7.1中的默認文本運算式避免了編譯器知道默認值時的冗余輸入,這是語法上的改進,CLR沒有任何變化,新代碼與C#編譯器早期版本構建的代碼100%兼容,
系列文章:
- [譯]C# 7系列,Part 1: Value Tuples 值元組
- [譯]C# 7系列,Part 2: Async Main 異步Main方法
- [譯]C# 7系列,Part 3: Default Literals 默認文本運算式 (本文)
- [譯]C# 7系列,Part 4: Discards 棄元
- [譯]C# 7系列,Part 5: private protected 訪問修飾符
- [譯]C# 7系列,Part 6: Read-only structs 只讀結構
- [譯]C# 7系列,Part 7: ref Returns ref回傳結果
- [譯]C# 7系列,Part 8: in Parameters in引數
- [譯]C# 7系列,Part 9: ref structs ref結構
- [譯]C# 7系列,Part 10: Span<T> and universal memory management Span<T>和統一記憶體管理 (完)
(本文)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/94872.html
標籤:C#
上一篇:C#運算式樹
