Build 2018 大會系列 Part I: The Future of C#

Part I 比較特別一點,其他篇會是濃縮重點為主,不過因為是關於語言的,除了把 //Build 2018 的 The Future of C# 中的重點節錄外,也順便自己也整理了一些 C# 7.0 ~ 7.3 的新特性,覺得 C# 7 的幾個新的特性的調整主要算是效能為主,讓我們往下看下去。

首先先強調了一次發展 C# 的策略,這邊就不翻譯了

  • We will keep growing C# to meet the evolving needs of developers and remain a state of the art programming language.
  • We will innovate aggressively, while being very careful to stay within the spirit of the language.
  • Given the diversity of the developer base, we will prefer language and performance improvements that benefit all or most developers
  • We will continue to empower the broader ecosystem and grow its role in C#’s future, while maintaining strong stewardship of design decisions to ensure continued coherence.

不過其實在2017 就有一篇文章描述這件事情 : Link

接著就是用 demo 來展示了一些 C# 7.1 ~ 7.3 的一些 feature;但其實去翻微軟的文件,有分別針對每個版本的做了詳細的列表。
下面就花了一些時間整理了一下 7.0 ~ 7.3 的我覺得比較重要或有趣的 feature,詳細有興趣的可以再依照下方的連結去仔細研究。

C# 7.0 :

  • 直接在 out 後面宣告
  • 新增 ValueTuple 支援 (要安裝 ValueTuple 的 NuGet)
  • 在out, ValueTuple, is/switch 的地方支援 discard 的語法
  • pattern matching
    • 可以使用 is 後面直接宣告變數
    • switch 可以支援 型別的
  • ref 的改進
    • 宣告 ref 的 local 變數
    • 宣告 ref 的 回傳值
  • local function
  • 更多可支援 expression body 宣告的地方
  • 新增 ValueTask 型別,必須要安裝 NuGet : System.Threading.Tasks.Extensions

C# 7.1 :

  • Main mehtod 支援 async
  • default 可以自動推導型態
  • Tuple 可以自動推導型態

C# 7.2 :

C# 7.3 :

接著就開始介紹 C# 8.0 正在嘗試的 feature ,在 BUILD 裡面提到的滿多在外面的文章讀到過的,有些很有趣,不過提到的因為還在制訂階段,都還有可能會變動,所以可能不要太在意~

  • Nullable Reference Type
  • Pattern Matchs 的增強

    搭配 expression body 把上面的程式改寫為:

    搭配 const pattern match (把上圖的 when 直接改成使用 const pattern match)

    接著用 var pattern ,把 FirstName 的值帶入宣告的 var fn(first name) 中來使用 (跟 is 的 pattern match 一樣的概念)。因為傳進來的是 Person 型態,所以開始的 Person 的 type pattern match 都可以省了。

    玩到一個極致就是把 Deconstruct 搭配上 recursive pattern (內心獨白:根本就是逼死人的寫法,很難懂啊XD)
  • Range
    • 新的 ^ 符號:代表從最後算回來的,型態是 Range,所以可以宣告 var last = ^1
    • 陣列中間也增加支援 Range 的使用,範例:
      • text[^1] 相當於 text[text.Length – 1]
      • text[1..^1] = text.SubString(1..^1) 相當於 text.SubString(1, text.Length – 2];
      • 要取長度 10 的陣列的 4~8 可以這樣寫 array[4..8]
      • 要取長度 n 的陣列從 4 ~ 最後可以這樣寫 array[4..^0] 也可以 array[4..]
      • 要取0 ~ 8 的陣列元素可以這樣寫 array[..8]
      • 當然如果前後都不給就是從頭取到尾
  • Async 改善
    • IAsyncDisposable
      • using 支援 await,範例: using await (…) {}
    • IAsyncEnumerable
      • foreach 支援 await,範例:forearch await (…) {}
  • Default Interface Member
  • Records
    簡單的宣告一個”紀錄型”的 class (A Model Class?)

//Build 2018 在 C# 介紹超多很神秘的語法與模式,讓開發人員足以改寫大量冗長的程式碼,甚至調整效能等,還有很多豐富的内容, Windows Team 也會繼續更新。謝謝。

This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.

This entry was posted in Windows and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *