因为在博客中给出的代码大多数都使用了C#6.0的新特性,如果各位对C#6.0还不了解,可以简单的看一下这篇随笔。o( ̄▽ ̄)d
先来看一个Point类
public class Point { public int X { get; set; } public int Y { get; set; } public Point(int x, int y) { X = x; Y = y; } public double Dist { get { return Math.Sqrt(X * X + Y * Y); } } ToString() { , X, Y); } }
现在我们一步步来看在C#6.0中的改进
1->在以前版本的C#代码中所有的自动属性都必须有Setter,但是现在可以没有了。注意,不能只有Setter
public class Point { public int X { get; } public int Y { get; } public Point(int x, int y) { X = x; Y = y; } public double Dist { get { return Math.Sqrt(X * X + Y * Y); } } ToString() { , X, Y); } }
2->同时现在也可以为自动属性直接设置初值,无需放到构造函数中
public class Point { public int X { get; } = 2; public int Y { get; set; } = 1; public Point(int x, int y) { X = x; Y = y; } public double Dist { get { return Math.Sqrt(X * X + Y * Y); } } ToString() { , X, Y); } }
3->使用静态成员
3.1在上面的代码中看一看到调用Sqrt函数需要使用Math开头,写一次两次还好,如果一个类中大规模使用Sqrt每次都要先写一个Math会不会太麻烦了!
现在我们来看看如何改进。
首先在命名空间中添加下面这一行代码
using static System.Math;
规则是 using + static + 静态类命名空间
于是Dist属性就可改成下面这样
public double Dist { get { return Sqrt(X * X + Y * Y); } }
3.2上面的规则也适用于枚举类型
using static Desktop.Color; namespace Desktop { enum Color { Yellow, Red } class Program { static void Main(string[] args) { Console.WriteLine(Yellow); Console.ReadKey(); } } }
4->关于String.Format()方法的改进
这是经典写法
, X, Y);
接下来一步步简化(先将String.Format用一个$代替)
, X, Y);
然后将0,1两个占位符直接换成X,Y
;
好的化简完成。
需要注意的是这个改进不能完全替代String.Format()比如下面这种情况
String.Format(, X > : );
5->对于Lambda表达式的改进
以前写匿名函数的时候可以写成一行,现在一般的函数也可以了
ToString()函数可以改写成如下形式
ToString() => $;
类似的属性可以改成这样
public double Dist => Sqrt(X * X + Y * Y);
注意属性是没有()的
简化后的Point类是这样的
public class Point { public int X { get; } = 2; public int Y { get; set; } = 1; public Point(int x, int y) { X = x; Y = y; } public double Dist => Sqrt(X * X + Y * Y); ToString() => $; }
6->索引初始化
先来看一段Json.Net的代码
public JObject ToJson() { var result = new JObject(); result[] = X; result[] = Y; return result; }
改进后的代码可以这么写
public JObject ToJson() { var result = new JObject() { [] = X, [] = Y }; return result; }
最终可以化简成一行代码
] = X, [] = Y };
7-> ?.运算符
?.运算符其实很简单,主要就是检查变量是否为null,如果不为null那就执行.
先来看一个函数,这个判断语句中大部分的检查都是在