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);