[C#6] 6-表达式形式的成员函数

0. 目录

C#6 新增特性目录

1. 老版本的代码

 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了,看下结构即可,都是普通的属性和方法而已):

2. 表达式形式的成员函数

我们看看新的写法有哪些简化:

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吧:

好吧,什么也不解释了,都一样还说啥,,,

3. Example

 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 }

这种新语法也仅仅只是语法简化,并无实质改变,编译结果和以前的老版本写法完全一致。

4. 参考

Method Expression Body Definitions

Property Expression Body Definitions

posted @ 2016-07-08 21:49  Timetombs  阅读(2410)  评论(1编辑  收藏  举报