昨天介紹了 C# 8.0 的新特性,但因為跟之前閱讀到的內容有出入,有些特性不在官方文件上面,才發現閱讀到的是 C# 8.0 與之後的更新內容。
除了之後的更新內容外,若有特性的範例比較完善,我也會一併分享。
Async streams
昨天有提到 IAsyncEnumerable
只有講到 foreach 在使用上的差異,而介面的實作為
1 | var enumerator = enumerable.GetAsyncEnumerator(); |
Target-typed new-expressions
簡報的範例比較好懂,比官方文件容易了解新特性。
1 | Triangle triangle = new Triangle (); |
可以取代成
1 | Triangle triangle = new (); |
簡報雖然沒有特別說明,但官方文件無以下的內容,我猜是之後可能會更新的東西
Enhanced using (pattern-based using)
不是很懂這個特性有什麼功用,簡報上看來是可以不實作介面(IDisposable),只實作成員(Dispose)就可以使用需要實作該介面成員的功能(using)。
1 | class Resoure { |
小提一下 using 算是 C# 的一個語法糖,可以幫你把 try-finally 語句縮短,舉個例子
1 | StreamWriter sw = new StreamWriter (path); |
經由 using 可寫成
1 | using (StreamWriter sw = new StreamWriter (path)) { |
編譯器出來的內容幾乎相等,也可以避免撰寫人員忘記釋放資源。
Null coalescing assignment
新的指派符號
1 | x = x ?? y; |
可以寫成
1 | x ??= y; |
簡報由此開始才是之後的內容
但上述的特性並無在 C# 8.0 的官方文件中,所以應該是簡報內容有誤,反正早晚會更新的,先看看也不差吧?
Negated-condition if statement
1 | if (!(shape is Triangle))) { ... } |
可以寫成以下幾種
1.增加關鍵字 not
1 | if (shape is not Triangle) { ... } |
2.可以在括弧外增加 !
1 | if !(shape is Triangle) { ... } |
3.新關鍵字 unless
我覺得很難實現的一個新關鍵字,畢竟它不是保留字,如果開發人員使用這個字來當作變數,那後果可能滿慘的。
1 | unless (shape is Triangle) { ... } |
Null-conditional await
1 | (task == null) ? null : await task; |
可以寫成
1 | await! task; |
Declaration expressions
1 | char ch; |
可以寫成
1 | while ((char ch = GetNextChar ()) == 'a' || ch == 'b') { ... } |
Dictionary Literals
1 | var x = dictionary<string, int> () { |
可以寫成
1 | var x = ["foo": 0, "bar": 1]; |
總結
沒有提到多重繼承的新特性,幾個月前有耳聞,但沒有在簡報內,不知道有沒有這回事。
這就是目前已知道的 C# 8.0 與之後的發展。
參考資料
C# 8 and Beyond