C# 中 10 個你真的應該學習(和使用!)的功能

來源:互聯網
上載者:User
如果你開始探索C#或決定擴充你的知識,那麼你應該學習這些有用的語言功能,這樣做有助於簡化代碼,避免錯誤,節省大量的時間。

  

1)async / await

使用async / await-pattern允許在執行阻塞操作時解除UI /當前線程的阻塞。async / await-pattern的工作原理是讓代碼繼續執行,即使在某些東西阻塞了執行(如Web請求)的情況下。


2)對象/數組/集合初始化器

通過使用對象、數組和集合初始化器,可以輕鬆地建立類、數組和集合的執行個體:


//一些示範類publicclassEmployee{ publicstringName { get; set;} publicDateTime StartDate { get; set;}} //使用初始化器建立employee Employee emp = newEmployee {Name= "John Smith", StartDate=DateTime.Now()};


上面的例子在單元測試中才真正有用,但在其他上下文中應該避免,因為類的執行個體應該使用建構函式建立。


3)Lambdas,謂詞,delegates和 閉包

在許多情況下(例如使用Linq時),這些功能實際上是必需的,確保學習何時以及如何使用它們。


4)??(空合并運算子)

?? – 運算子返回左側,只要它不為null;那樣的情況下返回右側:


//可能為nullvarsomeValue = service. GetValue(); vardefaultValue = 23//如果someValue為null,結果將為23varresult = someValue ?? defaultValue;


?? – 運算子可以連結:

stringanybody = parm1 ?? localDefault ?? globalDefault;


並且它可以用於將可空類型轉換為不可空:

vartotalPurchased = PurchaseQuantities.Sum(kvp => kvp.Value ?? 0);


5)$“{x}”(字串插值) ——C#6


這是C#6的一個新功能,可以讓你用高效和優雅的方式組裝字串:


//舊方法varsomeString = String.Format( "Some data: {0}, some more data: {1}", someVariable, someOtherVariable); //新方法varsomeString = $"Some data: {someVariable}, some more data: {someOtherVariable}";


你可以把C#運算式放在花括弧之間,這使得此字串插值非常強大。


6)?.(Null條件運算子) ——C#6

null條件運算子的工作方式如下:


//Null ifcustomer orcustomer.profile orcustomer.profile.age isnullvar currentAge = customer?.profile?.age;


沒有更多NullReferenceExceptions!


7)nameof Expression ——C#6

新出來的nameof-expression可能看起來不重要,但它真的有它的價值。當使用自動重構因子工具(如ReSharper)時,你有時需要通過名稱引用方法參數:


publicvoid PrintUserName( UsercurrentUser){ //The refactoring tool might miss the textual reference to current user below ifwe're renaming it if(currentUser == null) _logger. Error( "Argument currentUser is not provided"); //...}


你應該這樣使用它…


publicvoidPrintUserName(User currentUser){ //The refactoring tool will not miss this...if(currentUser == null) _logger.Error( $"Argument {nameof(currentUser)}is not provided"); //...} 8)屬性初始化器 ——C#6


屬性初始化器允許你聲明屬性的初始值:

publicclassUser{ publicGuidId{ get; } = Guid. NewGuid(); // ...}


使用屬性初始化器的一個好處是你不能聲明一個集合:嗯,因此使得屬性不可變。屬性初始化器與C#6主要建構函式文法一起工作。


9)as和is 運算子


is 運算子用於控制執行個體是否是特定類型,例如,如果你想看看是否可能轉換:


if( PersonisAdult){ //do stuff}


使用as運算子嘗試將執行個體轉換為類。如果不能轉換,它將返回null:


SomeType y = x asSomeType; if(y != null){ //do stuff} 10)yield關鍵字


yield 關鍵字允許提供帶有條目的IEnumerable介面。以下樣本將返回每個2的冪,冪指數從2到8(例如,2,4,8,16,32,64,128,256):


publicstaticIEnumerable Power(intnumber, intexponent){ intresult = 1; for( inti = 0; i < exponent; i++) { result = result * number; yieldreturnresult; }}


yield返回可以非常強大,如果它用於正確方式的話。它使你能夠懶惰地產生一系列對象,即,系統不必枚舉整個集合——它就會按需完成。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.