做为一门专为程(yu)序(fa)员(tang)考虑的语言,感觉一下来自微软的满满的恶意...
1. 字符串内联
在以前的版本中,经常使用的格式化字符串:函数
var s = String.Format("{0} is {1} year{{s}} old", p.Name, p.Age);
在 C# 6 中:this
//无格式 var s = $"{p.Name} is {p.Age} year{{s}} old"; //带格式 var s = $"{p.Name,20} is {p.Age:D3} year{{s}} old"; //带子表达式 var s = $"{p.Name} is {p.Age} year{(p.Age == 1 ? "" : "s")} old";
2. 空条件运算符
在以前的版本中对于 可空类型 或 动态类型 ,获取子元素每每较为复杂:spa
if(someSchool != null && someSchool.someGrade != null && someSchool.someGrade.someClass != null) { return someSchool.someGrade.someClass.someOne; }
在 C# 6 中,引入了新的运算符:code
return someSchool?.someGrade?.someClass?.someOne;
//也能够使用下标运算,例如
//return someArray?[0];
若是 ?. 运算符的左项为 null ,则直接返回 null 。
对于方法或者委托的执行,能够使用 Invoke:orm
someMethod?.Invoke(args);
3. nameof 表达式
能够直接返回传入变量的名称,而无需复杂的反射。索引
int someInt; Console.WriteLine(nameof(someInt)); //"someInt"
注:若是是前面带有命名空间和/或类名,只返回最后的变量名。
4. 索引初始化器
在 C# 6 中简化了对 Dictionary 的初始化方法:ci
var numbers = new Dictionary<int, string> { [7] = "seven", [9] = "nine", [13] = "thirteen" };
5. 条件异常处理
在 C# 6 中能够选择性地对某些异常进行处理,无需额外增长判断过程:字符串
try { … } catch (MyException e) if (myfilter(e)) { … }
6. 属性初始化器
在 C# 6 中能够直接对属性进行初始化:get
public class Customer { public string First { get; set; } = "Jane"; public string Last { get; set; } = "Doe"; }
以及能够相似定义只读的属性。
7. 成员函数的 lambda 定义
在 C# 6 中能够使用 lambda 表达式来定义成员方法。string
public class Point { public Point Move(int dx, int dy) => new Point(x + dx, y + dy); public static Complex operator +(Complex a, Complex b) => a.Add(b); public static implicit operator string(Person p) => $"{p.First}, {p.Last}"; }
8. 结构体的参数构造函数
在 C# 6 中能够建立结构体的带参数构造函数。
struct Person { public string Name { get; } public int Age { get; } public Person(string name, int age) { Name = name; Age = age; } public Person() : this("Jane Doe", 37) { } }
9. using 静态类
在 C# 6 中 using 除了能够用于命名空间也能够用于静态类。
using System.Console; using System.Math; class Program { static void Main() { WriteLine(Sqrt(3*3 + 4*4)); } }
来自:http://www.zhihu.com/question/27421302