0. 目录
1. 老版本的代码
internal class Person
{
public string FirstName { get; set; }
public string LastName { get; set; } public string FullName
{
get { return FirstName + LastName; }
} public override string ToString()
{
return string.Format("[firstname={0},lastname={1}]", FirstName, LastName);
}
}
通常情况下,有些简单的只读属性和方法只有一行代码,但是我们也不得不按照繁琐的语法去实现它。C#6带了了一种和lambda语法高度一致的精简语法来帮助我们简化这些语法。先看看老版本的IL代码(这里我就不展开IL了,看下结构即可,都是普通的属性和方法而已):
2. 表达式形式的成员函数
我们看看新的写法有哪些简化:
internal class Person
{
public string FirstName { get; set; }
public string LastName { get; set; } public string FullName => FirstName + LastName; public override string ToString() => string.Format("[firstname={0},lastname={1}]", FirstName, LastName);
}
对于属性来说,省略掉了get声明,方法则省掉了方法的{},均使用=>语法形式来表示。看看IL吧:
好吧,什么也不解释了,都一样还说啥,,,
3. Example
internal class Point
{
public int X { get; private set; }
public int Y { get; private set; } public Point(int x, int y)
{
this.X = x;
this.Y = y;
} public Point Add(Point other)
{
return new Point(this.X + other.X, this.Y + other.Y);
} //方法1,有返回值
public Point Move(int dx, int dy) => new Point(X + dx, Y + dy); //方法2,无返回值
public void Print() => Console.WriteLine(X + "," + Y); //静态方法,操作符重载
public static Point operator +(Point a, Point b) => a.Add(b); //只读属性,只能用于只读属性
public string Display => "[" + X + "," + Y + "]"; //索引器
public int this[long id] => ;
} internal class Program
{
private static void Main()
{
Point p1 = new Point(, );
Point p2 = new Point(, );
Point p3 = p1 + p2;
//输出:[3,4]
Console.WriteLine(p3.Display);
}
}
这种新语法也仅仅只是语法简化,并无实质改变,编译结果和以前的老版本写法完全一致。