簡介
VS 2015中已經包含C# 6.0. C#在釋出不同版本時,C#總是會有新特性,比如C#3.0中出現LINQ,C#4.0中的動態特性,c#5.0中的非同步操作等。.
C# 6.0中與增加了不少新的特性,幫助開發人員更好的程式設計。
下面的示例需要下載vs2015,這樣才會有C#6.0環境,主要的新特性有:
- 使用Static引數,直接引用類中的方法或屬性,不用每次都帶上類名。
using System;
using static System.Console;
namespace CSharp6FeaturesDemo
{
class Program
{
static void Main(string[] args)
{
WriteLine("This is demo for C# 6.0 New Features");
ReadLine();
}
}
} - 成員屬性自動初始化,在定義屬性時,即可通過簡單的程式碼初始化屬性的值,而不用在建構函式中初始化。
public class Employee
{
public Guid EmployeeId { get; set; } = Guid.NewGuid();
public string FirstName { get; set; } = "Mukesh";
public string LastName { get; set; } = "Kumar";
public string FullName { get { return string.Format("{0} {1}", FirstName, LastName); } }
} - 集合中初始化成員的方式有所變化,變得更直觀。
Dictionary<int, string> myDictionary = new Dictionary<int, string>()
{
[1] = "Mukesh Kumar",
[2] = "Rahul Rathor",
[3] = "Yaduveer Saini",
[4] = "Banke Chamber"
}; - 字串格式化,以前要使用string.format("{0}-{1}",v1, v2); 來格式化輸出,使用數字,容易出錯,現在直接使用變數名
Console.WriteLine($"The Full Name of Employee {firstName} {lastName}");
C#6.0中,可以使用lambda表示式在一行內定義一個簡單的函式,而不是傳統的需要定義一個完整的函式。
6.0之前6.0中public static string GetFullName(string firstName, string lastName)
{
return string.Format("{0} {1}", firstName, lastName);
}public static string GetFullName(string firstName, string lastName) => firstName + " " + lastName;
- C#6.0之前,一個屬性需要同時定義get和set方法,即使set方法根本不需要,比如只讀的屬性。在C#6.0中,可以只定義一個get方法,並設定屬性的初始值
string FirstName { get; } = "Mukesh";
- 異常處理改進,以前異常處理中,需要在一個catch塊中判斷每個異常值的情況,然後執行不同的程式碼,而C#6.0中,可以定義多個 catch塊,根據不同異常值處理不同的程式碼。
try
{
throw new Exception(errorCode.ToString());
}
catch (Exception ex) when (ex.Message.Equals("404"))
{ WriteLine("This is Http Error"); }
catch (Exception ex) when (ex.Message.Equals("401"))
{ WriteLine("This is Unathorized Error"); }
catch (Exception ex) when (ex.Message.Equals("403"))
{ WriteLine("Forbidden"); } - Null值判斷改進,以前操作某個變數需要判斷是否null,否則程式丟擲異常;在C#6.0中,可以使用一個簡單的問號?即可自動判斷是否null,如果是,則輸出null值。
//No need to check null in if condition
//null operator ? will check and return null if value is not there
WriteLine(employees.FirstOrDefault()?.Name);
//set the default value if value is null
WriteLine(employees.FirstOrDefault()?.Name ?? "My Value"); - 變數宣告改進,以前宣告一個變數,用於從函式中返回值,需要在函式外定義,在C#6.0中,可直接在函式呼叫時定義變數。
static void Main(string[] args)
{
if (int.TryParse("20", out var result)) {
return result;
}
return 0; // result is out of scope
}
具體內容和示例程式碼可參考:
http://www.codeproject.com/Articles/1070659/All-About-Csharp-New-Features