ASP.NETCore1C#6.0新語法
阿新 • • 發佈:2020-07-08
1.字串嵌入值(String interpolation)
Console.WriteLine($"年齡:{{{this.Age}}} 生日:{{{this.BirthDay.ToString("yyyy -MM-dd")}}}"); Console.WriteLine($"{(this.Age <= 22 ? "小鮮肉" : "老鮮肉")}");
2.匯入靜態類(Using Static)
using static System.Math; Console.WriteLine($"之前的使用方式: {Math.Pow(4, 2)}"); Console.WriteLine($"匯入後可直接使用方法: {Pow(4, 2)}");
3.空值運算子(Null-conditional operators)
int? iValue = 10; Console.WriteLine(iValue?.ToString());//不需要判斷是否為空 string name = null; Console.WriteLine(name?.ToString());
4.物件初始化器(Index Initializers)
IDictionary<int, string> dictOld = new Dictionary<int, string>() { { 1,"first"}, { 2,"second"} }; IDictionary<int, string> dictNew = new Dictionary<int, string>() { [4] = "first", [5] = "second" };
5.異常過濾器(Exception filters)
int exceptionValue = 10; try { Int32.Parse("s"); } catch (Exception e) when (exceptionValue > 1)//滿足條件才進入catch { Console.WriteLine("catch"); //return; }
6.nameof表示式 (nameof expressions),方便修改變數名
string str = "哈哈哈哈"; Console.WriteLine($"變數str值為:{str}"); Console.WriteLine($"變數{nameof(str)}值為:{str}");
7.在屬性/方法裡使用Lambda表示式(Expression bodies on property-like function members)
public string NameFormat => string.Format("姓名: {0}", "summit"); public void Print() => Console.WriteLine(Name);