代码改变世界

感受C#6.0新语法

2015-05-06 21:51  C#与.NET探索者  阅读(446)  评论(0编辑  收藏  举报

作为一门专为程(yu)序(fa)员(tang)考虑的语言,感受一下来自微软的满满的恶意...

1. 字符串内联
在之前的版本中,常用的格式化字符串:

var s = String.Format("{0} is {1} year{{s}} old", p.Name, p.Age);

在 C# 6 中:

//无格式
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. 空条件运算符
在之前的版本中对于 可空类型 或 动态类型 ,获取子元素往往较为复杂:

if(someSchool != null && someSchool.someGrade != null && someSchool.someGrade.someClass != null)
{
    return someSchool.someGrade.someClass.someOne;
}

在 C# 6 中,引入了新的运算符:

return someSchool?.someGrade?.someClass?.someOne;
//也可以使用下标运算,例如
//return someArray?[0];

如果 ?. 运算符的左项为 null ,则直接返回 null 。
对于方法或者委托的执行,可以使用 Invoke:

someMethod?.Invoke(args);


3. nameof 表达式
可以直接返回传入变量的名称,而无需复杂的反射。

int someInt;
Console.WriteLine(nameof(someInt)); //"someInt"

注:如果是前面带有命名空间和/或类名,只返回最后的变量名。

4. 索引初始化器
在 C# 6 中简化了对 Dictionary 的初始化方法:

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 中可以直接对属性进行初始化:

public class Customer 
{ 
    public string First { get; set; } = "Jane"; 
    public string Last { get; set; } = "Doe"; 
}

以及可以类似定义只读的属性。

7. 成员函数的 lambda 定义
在 C# 6 中可以使用 lambda 表达式来定义成员方法。

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