屬性
什么是自動屬性
不需要定義欄位 ,在編譯時生產對應欄位,相當于是微軟提供的一個“語法糖”
public int Age { get; set; }
只讀自動屬性
使用訪問修飾符修飾set
public string Name { get; private set; }
也可以只申明get訪問器
public string Name { get; }
自動屬性初始化
public List<string> Names { get; set; } = new List<string>();
使用運算式初始化
public override string ToString() => Name; public string FirstName { get; set; } public string LastName { get; set; } public string FullName => $"{FirstName} {LastName}";
using static
用于匯入單個類的靜態方法
using static System.Math; private double CalculateArea(double r) => PI * r * r;
可以使用PI來表示Math.PI
Null條件運算子
private void EmptyJudgment() { var result = Names.Where(x => x.Contains("12")); var list = result?.ToList(); var list2 = list ?? new List<string>(); }
使用 ?. 替換 . 如果result為null后面的ToList不會生效,回傳值list為空
??當list不為空list2=list,如果為null則將??右側賦值給list2
字串內嵌
public string FullName => $"{FirstName} {LastName}";
字串前添加$,在{}內可以使用C#代碼
例外
過濾器
private void ExceptionFilter() { try { } catch (Exception e) when(e.Message.Contains("400")) { Console.WriteLine(e); throw; } }
在catch后使用when關鍵字進行條件篩選
finally塊中使用await
private async void AwaitAtException() { try { } catch (Exception e) { Console.WriteLine(e); throw; } finally { await Task.Delay(1000); } }
Nameof
private string NameOfExpression() { return nameof(List); }
nameof運算式的計算結果為符號的名稱,例子回傳值為“List”
使用索引器為集合初始化
public Dictionary<int, string> Dictionary { get; set; } = new Dictionary<int, string> { [400] = "Page Not Found", [500] = "Server Error" };
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/6406.html
標籤:C#
上一篇:C#中foreach的實作原理
下一篇:C#7.0新特性
