原文地址:http://www.oschina.net/translate/briefly-exploring-csharp-new-featuresasp.net
幾周前我在不一樣的地方讀到了有關C#6的一些新特性。我就決定把它們都收集到一塊兒,若是你尚未讀過,就能夠一次性把它們都過一遍。它們中的一些可能不會如預期那樣神奇,但那也只是目前的更新。異步
你能夠經過下載VS2014或者安裝這裏針對visual studio2013的Roslyn包來獲取它們。優化
那麼讓咱們看看吧:網站
使用它的目的是簡化基於索引的字符串,僅此而已。它不是像如今C#的一些動態特性,由於其內部使用了正規的索引功能. 爲了編譯理解請看下面的示例:this
var col = new Dictionary<string, string>() { $first = "Hassan" }; //Assign value to member //the old way: col.$first = "Hassan"; //the new way: col["first"] = "Hassan";
異常過濾器已經被VB編譯器支持了,而如今它也被引入了C#。異常過濾器讓你能夠爲一個catch塊指定一個條件. 這個catch塊就只會在條件被知足時被執行 , 這是我最喜歡的特性,那麼就讓咱們來看看示例吧:spa
try { throw new Exception("Me"); } catch (Exception ex) if (ex.Message == "You") { // this one will not execute. } catch (Exception ex) if (ex.Message == "Me") { // this one will execute }
據我所知,沒有人知道C# 5中catch和finally代碼塊內await關鍵字不可用的緣由,不管何種寫法它都是不可用的。這點很好由於開發人員常常想查看I/O操做日誌,爲了將捕捉到的異常信息記錄到日誌中,此時須要異步進行。.net
try { DoSomething(); } catch (Exception) { await LogService.LogAsync(ex); }
這個特性容許開發人員在表達式中定義一個變量。這點很簡單但很實用。過去我用asp.net作了許多的網站,下面是我經常使用的代碼: 日誌
long id; if (!long.TryParse(Request.QureyString["Id"], out id)) { }
優化後的代碼:code
if (!long.TryParse(Request.QureyString["Id"], out long id)) { }
這一特性容許你在一個using語句中指定一個特定的類型,此後這個類型的全部靜態成員都能在後面的子句中使用了.blog
1 using System.Console; 2 3 namespace ConsoleApplication10 4 { 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 //Use writeLine method of Console class 10 //Without specifying the class name 11 WriteLine("Hellow World"); 12 } 13 } 14 }
C# 6 自動溫馨化屬性就像是在聲明位置的域。這裏惟一須要知道的是這個初始化不會致使setter方法不會在內部被調用. 後臺的域值是直接被設置的,下面是示例:
public class Person { // You can use this feature on both //getter only and setter / getter only properties public string FirstName { get; set; } = "Hassan"; public string LastName { get; } = "Hashemi"; }
呼哈哈,主構造器將幫你消除在獲取構造器參數並將其設置到類的域上,以支持後面的操做,這一痛苦. 這真的頗有用。這個特性的主要目的是使用構造器參數進行初始化。當聲明瞭主構造器時,全部其它的構造器都須要使用 :this() 來調用這個主構造器.
最後是下面的示例:
//this is the primary constructor: class Person(string firstName, string lastName) { public string FirstName { get; set; } = firstName; public string LastName { get; } = lastName; }
要注意主構造器的調用是在類的頂部.