C#6 新增特性目錄
1 internal class Person 2 { 3 public string FirstName { get; set; } 4 public string LastName { get; set; } 5 6 public string FullName 7 { 8 get { return FirstName + LastName; } 9 } 10 11 public override string ToString() 12 { 13 return string.Format("[firstname={0},lastname={1}]", FirstName, LastName); 14 } 15 }
通常情況下,有些簡單的只讀屬性和方法只有一行代碼,但是我們也不得不按照繁瑣的語法去實現它。C#6帶了了一種和lambda語法高度一致的精簡語法來幫助我們簡化這些語法。先看看老版本的IL代碼(這裡我就不展開IL了,看下結構即可,都是普通的屬性和方法而已):
我們看看新的寫法有哪些簡化:
1 internal class Person 2 { 3 public string FirstName { get; set; } 4 public string LastName { get; set; } 5 6 public string FullName => FirstName + LastName; 7 8 public override string ToString() => string.Format("[firstname={0},lastname={1}]", FirstName, LastName); 9 }
對於屬性來說,省略掉了get聲明,方法則省掉了方法的{},均使用=>語法形式來表示。看看IL吧:
好吧,什麼也不解釋了,都一樣還說啥,,,
1 internal class Point 2 { 3 public int X { get; private set; } 4 public int Y { get; private set; } 5 6 public Point(int x, int y) 7 { 8 this.X = x; 9 this.Y = y; 10 } 11 12 public Point Add(Point other) 13 { 14 return new Point(this.X + other.X, this.Y + other.Y); 15 } 16 17 //方法1,有返回值 18 public Point Move(int dx, int dy) => new Point(X + dx, Y + dy); 19 20 //方法2,無返回值 21 public void Print() => Console.WriteLine(X + "," + Y); 22 23 //靜態方法,操作符重載 24 public static Point operator +(Point a, Point b) => a.Add(b); 25 26 //只讀屬性,只能用於只讀屬性 27 public string Display => "[" + X + "," + Y + "]"; 28 29 //索引器 30 public int this[long id] => 1; 31 } 32 33 internal class Program 34 { 35 private static void Main() 36 { 37 Point p1 = new Point(1, 1); 38 Point p2 = new Point(2, 3); 39 Point p3 = p1 + p2; 40 //輸出:[3,4] 41 Console.WriteLine(p3.Display); 42 } 43 }
這種新語法也僅僅只是語法簡化,並無實質改變,編譯結果和以前的老版本寫法完全一致。
Method Expression Body Definitions
Property Expression Body Definitions