與Mads Torgersen一起提前預覽C# 7

jopen 9年前發布 | 5K 次閱讀 C#

Channel 9的Seth Juarez訪問了C#的產品經理Mads Torgersen,談及關于 下個版本的C#語言的開發 ,代號C# 7。 除一些其它特性外,還提及三個主要的特性:pattern matching、tuple syntax和nullable references。

Pattern Matching

Mads開場講解由于系統更加分散,結構化數據頻繁地通過電線交換。由于這些數據傳送并不伴隨其操作集合,肯定有方法能更容易地操作這些數據。這就是函數式編程突出的領域,尤其是使用pattern matching。

// Moving a shape using C# 6
void Move (Shape s) {
  var r = s as Rectangle;
  if (r != null) { // Move the rectangle }
  var c as Circle;
  if (x != null) { // Move the circle }
}

// Moving a shape using pattern matching void move (Shape s) { match (s) { (Rectangle r) => // Move rectangle (Circle c) => // Move circle default => // Handle default or throw } }</pre>

Tuple syntax

Tuple syntax使得臨時聚合數據成為可能。Mads講解道,tuples可以命名其成員,因此使得辨認tuple的各個成員更加容易。

// Current syntax
TupleCompute()
// Tuple syntax
(int x, int y) Compute()

// Call the method var (x,y) = Compute()</pre>

接下來更詳細的一個例子是狀態機的實現。結合pattern matching,寫出以下幾行語法簡明的代碼:

match (state, input) {
    (State.Init, Event.Go) => { // Process the input }
    (State.Init, Event.Stop) => { // Process the input}
    (_, _) => { // handle invalid state }
}

Nullable reference type

靜態地避免空引用異常以前已經嘗試過了,但Mads說團隊將提供另一種方案。目的是能幫助人們獲得更安全的行為而不需強加太多限制或引入破壞性更新。這個想法本質上是提議為引用添加可選類型。然而, 在評論中 Mads假定將引用表達為nullable比將其表達為non-nullable更加重要。

我覺得nullable reference type是特性中最重要的部分。因為這是個全新的(而且不受爭議的)語法,就其本身而言它沒有破壞任何現有的代碼 - 連一個警告也沒有。我們使其可行的方法是,當你解除其中一個引用 - 例如“string?” - 我們只會在你沒有檢查null的時候給你一個警告。

</div>

必須注意的是這都還在設計流程的早期階段,而且這些特性和語法還只是有待探索的想法而已。因此Mads說:“所有東西已經在臺面上了”。更多現有進展的信息可以瀏覽 GitHub

查看英文原文: Early View of C# 7 with Mads Torgersen

原文 http://www.infoq.com/cn/news/2015/11/csharp-7-sneak-peek

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!