C#6.0新特性

C#6.0新特性


首先

自動屬性初始化增強

複製代碼
public class Customer
{
    public string First { get; set; } = "Jane";
    public string Last { get; set; } = "Doe";
}

複製代碼

 

public class Customer
{
    public string First { get; } = "Jane";
    public string Last { get; } = "Doe";
}
複製代碼
public class Customer
{
   //只讀的屬性  
    public string Name { get; };
    //在初始化方法中賦值,可行~
    public Customer(string first, string last)
    {
        Name = first + " " + last;
    }
}
複製代碼

在C#5.0中是不可行的 如下圖:

 

方法函數支持lambda寫法 如下:

public void Print() => Console.WriteLine(First + " " + Last);

支持直接導入命名空間一樣導入靜態類,而不用在代碼中使用靜態類名 如下:

複製代碼
//靜態導入Console
using static System.Console;
using static System.Math;
using static System.DayOfWeek;
class Program
{
    static void Main()
    {
        //直接使用方法而不用Console.WriteLine
        WriteLine(Sqrt(3*3 + 4*4)); 
        WriteLine(Friday - Monday); 
    }
}
複製代碼

擴展方法,(這個不是很懂,解釋不好請原諒)

在Main類中靜態的導入你要擴展的類型,然後寫你需要擴展的方法..?.. - -,不懂..

複製代碼
using static System.Linq.Enumerable; // The type, not the namespace
class Program
{
    static void Main()
    {
        var range = Range(5, 17);                // Ok: not extension
        var odd = Where(range, i => i % 2 == 1); // Error, not in scope
        var even = range.Where(i => i % 2 == 0); // Ok
    }
}
複製代碼

 

非空的語法糖如下:

int? first = customers?[0].Orders.Count();
//上面的寫法等同於下面
int? first = (customers != null) ? customers[0].Orders.Count() : null;

 

字符串格式化新玩法:

複製代碼
//原來的,我們需要這樣..
var s = String.Format("{0} is {1} year{{s}} old", p.Name, p.Age);

//C#6.0中,直接如下:
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";
複製代碼

 

索引初始化:

var numbers = new Dictionary<int, string> {
    [7] = "seven",
    [9] = "nine",
    [13] = "thirteen"
};

異常過濾器:

如果When中用括號括起來的表達式計算結果爲true,catch塊中運行,否則異常持續。

( - -,然而我也並沒有搞懂..求大神解釋..)

 

try { … }
catch (MyException e) when (myfilter(e))
{
    …
}

可異步等待的Catch塊:

複製代碼
Resource res = null;
try
{
    res = await Resource.OpenAsync(…);       // You could do this.
    …
} 
catch(ResourceException e)
{
    await Resource.LogAsync(res, e);         // Now you can do this …
}
finally
{
    if (res != null) await res.CloseAsync(); // … and this.
}
複製代碼

基本到此就結束了, - -,水平有限.不好與不完善的地方請指出..免得誤導大家..

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章