不須要定義字段 ,在編譯時生產對應字段,至關因而微軟提供的一個「語法糖」async
public int Age { get; set; } ide
使用訪問修飾符修飾setspa
public string Name { get; private set; }code
也能夠只申明get訪問器blog
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}";
用於導入單個類的靜態方法get
using static System.Math; private double CalculateArea(double r) => PI * r * r;
可使用PI來表示Math.PIstring
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爲空it
??當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關鍵字進行條件篩選
private async void AwaitAtException() { try { } catch (Exception e) { Console.WriteLine(e); throw; } finally { await Task.Delay(1000); } }
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" };