C# 8.0 與未來

前天介紹了 C# 8.0 的新特性,但因為跟之前閱讀到的內容有出入,有些特性不在官方文件上面,才發現閱讀到的是 C# 8.0 與之後的更新內容。

除了之後的更新內容外,若有特性的範例比較完善,我也會一併分享。

Async streams

昨天有提到 IAsyncEnumerable 為 IEnumerable 的非同步版本。

只有講到 foreach 在使用上的差異,而介面的實作為

var enumerator = enumerable.GetAsyncEnumerator();
try {
  while (await enumerator.MoveNextAsync ()){
    T item = enumerator.Current;
    ...
  }
}
finally {
  await enumerator.DisposeAsync ();
}

Target-typed new-expressions

簡報的範例比較好懂,比官方文件容易了解新特性。

Triangle triangle = new Triangle ();

Dictionary<string, List<int>> field = new Dictionary<string, List<int>> () {
  {"item", new List<int> () { 1 ,2, 3 }}
};

可以取代成

Triangle triangle = new ();

Dictionary<string, List<int>> field = new () {
  {"item", new () { 1 ,2, 3 }}
};

簡報雖然沒有特別說明,但官方文件無以下的內容,我猜是之後可能會更新的東西

Enhanced using (pattern-based using)

不是很懂這個特性有什麼功用,簡報上看來是可以不實作介面(IDisposable),只實作成員(Dispose)就可以使用需要實作該介面成員的功能(using)。

class Resoure {
  public void Dispose () { ... }
}

using (var resoure = new Resoure ()) {
  ...
}

小提一下 using 算是 C# 的一個語法糖,可以幫你把 try-finally 語句縮短,舉個例子

StreamWriter sw = new StreamWriter (path);
try {
  sw.Write ("something");
  } 
finally {
  sw.Dispose ();
}

經由 using 可寫成

using (StreamWriter sw = new StreamWriter (path)) {
  sw.Write ("something");
}

編譯器出來的內容幾乎相等,也可以避免撰寫人員忘記釋放資源。

Null coalescing assignment

新的指派符號

x = x ?? y;

可以寫成

x ??= y;

簡報由此開始才是之後的內容

但上述的特性並無在 C# 8.0 的官方文件中,所以應該是簡報內容有誤,反正早晚會更新的,先看看也不差吧?

Negated-condition if statement

if (!(shape is Triangle))) { ... }

可以寫成以下幾種

1.增加關鍵字 not

if (shape is not Triangle) { ... }

2.可以在括弧外增加 !

if !(shape is Triangle) { ... }

3.新關鍵字 unless

我覺得很難實現的一個新關鍵字,畢竟它不是保留字,如果開發人員使用這個字來當作變數,那後果可能滿慘的。

unless (shape is Triangle) { ... }

Null-conditional await

(task == null) ? null : await task;

可以寫成

await! task;

Declaration expressions

char ch;
while ((ch = GetNextChar ()) == 'a' || ch == 'b') { ... }

可以寫成

while ((char ch = GetNextChar ()) == 'a' || ch == 'b') { ... }

Dictionary Literals

var x = dictionary<string, int> () {
  {"foo", 0},
  {"bar", 1}
}

可以寫成

var x = ["foo": 0, "bar": 1];

總結

沒有提到多重繼承的新特性,幾個月前有耳聞,但沒有在簡報內,不知道有沒有這回事。

這就是目前已知道的 C# 8.0 與之後的發展。

參考資料
C# 8 and Beyond