1、自動只讀屬性
之前屬性為如下所示,屬性賦值需在建構式對其初始化
1 public int Id { get; set; }
2 public string Name { get; set; }
更新后
public string Name { get; set; } = "summit";
public int Age { get; set; } = 22;
public DateTime BirthDay { get; set; } = DateTime.Now.AddYears(-20);
public IList<int> AgeList
{
get;
set;
} = new List<int> { 10, 20, 30, 40, 50 };
2、直接參考靜態類
如果之前呼叫靜態類中的方法,如下書寫:
Math.Abs(20d);
更新后:
using static System.Math;
private void Form1_Load(object sender, EventArgs e)
{
Abs(20d);
}
3、Null 條件運算子
之前在使用物件時,需要先進性判斷是否為null
if (student!=null)
{
string fullName = student.FullName;
}
else
{
//……
}
更新后:
string fullName = student?.FullName; //如果student為空則回傳Null,不為空則回傳.FullNaem,注意!得到的結果一定是要支持null
4、字串內插
string str = $"{firstName}和{lastName}"
5、例外篩選器
try
{
}
catch(Exception e) when(e.Message.Contains("例外過濾,把符合條件的例外捕獲")
{
}
6、nameof 運算式可生成變數、型別或成員的名稱作為字串常量
Console.WriteLine(nameof(System.Collections.Generic)); // output: Generic
Console.WriteLine(nameof(List<int>)); // output: List
7、使用索引器初始化對字典進行賦值
Dictionary<int, string> messages = new Dictionary<int, string>
{
{ 404, "Page not Found"},
{ 302, "Page moved, but left a forwarding address."},
{ 500, "The web server can't come out to play today."}
};
同時也可以這樣通過索引的方式進行賦值
Dictionary<int, string> webErrors = new Dictionary<int, string>
{
[404] = "Page not Found",
[302] = "Page moved, but left a forwarding address.",
[500] = "The web server can't come out to play today."
};
8、在屬性/方法里面使用Lambda運算式
public string NameFormat => string.Format("姓名: {0}", "summit");
public void Print() => Console.WriteLine(Name);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/238115.html
標籤:其他
