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

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

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

2)對象/數組/集合初始化器
通過使用對象、數組和集合初始化器,可以輕鬆地創建類、數組和集合的實例:
//一些演示類public class Employee { public string Name {get; set;} public DateTime StartDate {get; set;}}//使用初始化器創建employee Employee emp = new Employee {Name="John Smith", StartDate=DateTime.Now()};
上面的例子在單元測試中才真正有用,但在其他上下文中應該避免,因爲類的實例應該使用構造函數創建。

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

4)??(空合併運算符)
?? – 運算符返回左側,只要它不爲null;那樣的情況下返回右側:
//可能爲nullvar someValue = service.GetValue();var defaultValue = 23//如果someValue爲null,結果將爲23var result = someValue ?? defaultValue;
?? – 運算符可以鏈接:
string anybody = parm1 ?? localDefault ?? globalDefault;
並且它可以用於將可空類型轉換爲不可空:
var totalPurchased = PurchaseQuantities.Sum(kvp => kvp.Value ?? 0);

5)$“{x}”(字符串插值) ——C#6
這是C#6的一個新功能,可以讓你用高效和優雅的方式組裝字符串:
//舊方法var someString = String.Format("Some data: {0}, some more data: {1}", someVariable, someOtherVariable);//新方法var someString = $"Some data: {someVariable}, some more data: {someOtherVariable}";
你可以把C#表達式放在花括號之間,這使得此字符串插值非常強大。

6)?.(Null條件運算符) ——C#6
null條件運算符的工作方式如下:
//Null if customer or customer.profile or customer.profile.age is nullvar currentAge = customer?.profile?.age;
沒有更多NullReferenceExceptions!

7)nameof Expression ——C#6
新出來的nameof-expression可能看起來不重要,但它真的有它的價值。當使用自動重構因子工具(如ReSharper)時,你有時需要通過名稱引用方法參數:
public void PrintUserName(User currentUser){ //The refactoring tool might miss the textual reference to current user below if we're renaming it if(currentUser == null) _logger.Error("Argument currentUser is not provided"); //...}
你應該這樣使用它…
public void PrintUserName(User currentUser){ //The refactoring tool will not miss this... if(currentUser == null) _logger.Error($"Argument {nameof(currentUser)} is not provided"); //...}

8)屬性初始化器 ——C#6
屬性初始化器允許你聲明屬性的初始值:
public class User{ public Guid Id { get; } = Guid.NewGuid(); // ...}
使用屬性初始化器的一個好處是你不能聲明一個集合:嗯,因此使得屬性不可變。屬性初始化器與C#6主要構造函數語法一起工作。

9)as和is 運算符
is 運算符用於控制實例是否是特定類型,例如,如果你想看看是否可能轉換:
if (Person is Adult){ //do stuff}
使用as運算符嘗試將實例轉換爲類。如果不能轉換,它將返回null:
SomeType y = x as SomeType;if (y != null){ //do stuff}10)yield 關鍵字
yield 關鍵字允許提供帶有條目的IEnumerable接口。 以下示例將返回每個2的冪,冪指數從2到8(例如,2,4,8,16,32,64,128,256):
public static IEnumerable Power(int number, int exponent){ int result = 1; for (int i = 0; i < exponent; i++) { result = result * number; yield return result; }}
yield返回可以非常強大,如果它用於正確方式的話。 它使你能夠懶惰地生成一系列對象,即,系統不必枚舉整個集合——它就會按需完成。
黑馬匠心之作C++教程
配套資料(提取碼:qwwn)

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