people类
public class People { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } /// <summary> ///C#6新语法. :8.自动实现的属性初始化器 /// </summary> public DateTime BirthDay { get; set; } = DateTime.Now.AddYears(-22); /// <summary> /// C#6新语法:在属性/方法里使用Lambda表达式(Expression bodies on property-like function members) /// </summary> public string NameFormat => string.Format("姓名:{0}", "NameFormat"); /// <summary> /// C#6新语法:在属性/方法里使用Lambda表达式(Expression bodies on property-like function members) /// </summary> public void Print() => WriteLine(NameFormat); }
1.导入静态类:
之前的写法:静态类.
{ Console.WriteLine("Hello!");
Console.WriteLine($"之前的使用方式[静态类.]:{Math.Max(2, 3)}"); }
C#6的写法:
//引入命名空间 using static System.Math; using static System.Console;
WriteLine("Hello!"); WriteLine($"现在的使用方式引入命名空间,这边直接调用:{ Max(2, 3)}");
2.字符串嵌入值
#region 2.字符串嵌入值(String interpolation) { WriteLine($"Id:{people.Id} 姓名:{people.Name} 生日:{people.BirthDay.ToString("yyyy-MM-dd")}"); WriteLine($"{(people.Age >= 25 ? "腊肉" : "鲜肉")}"); WriteLine($"Id:{{{people.Id}}} 姓名:{{{people.Name}}}"); } #endregion
3.空值运算符
#region 3.空值运算符(Null-conditional operators) 可空判断 { int? iValue = null; string sValue = iValue?.ToString();//string sValue = iValue.ToString();不判断会报错 iValue = Convert.ToInt32(sValue); WriteLine($"iValue:{iValue}"); string sName = ""; WriteLine($"sName:{sName?.ToString()}"); } #endregion
4.对象初始化器
#region 4.对象初始化器(Index Initializers) { //之前通过add方法,add keyvalue进去 { IDictionary<int, string> dictOld = new Dictionary<int, string>() { }; dictOld.Add(1, "M"); dictOld.Add(2, "A"); dictOld.Add(3, "X"); foreach (var keyValue in dictOld) { Console.WriteLine($"key:{keyValue.Key},value:{keyValue.Value}"); } } { IDictionary<int, string> dictOld1 = new Dictionary<int, string>() { { 1,"M"},{ 2,"A"},{ 3,"X"} }; } { //通过索引的方式给字段进行初始化 IDictionary<int, DateTime> dictNew = new Dictionary<int, DateTime>() { [1] = DateTime.Now, [2] = DateTime.Now.AddDays(-1), [3] = DateTime.Now.AddDays(-2) }; foreach (var keyValue in dictNew) { Console.WriteLine($"key:{keyValue.Key},value:{keyValue.Value}"); } } } #endregion
5.异常过滤器
#region 5.异常过滤器(Exception filters) { int iExceptionValue = 2; try { Int32.Parse("S");//Parse类型强制转换 } catch (Exception e) when (iExceptionValue > 1) { WriteLine(e.Message); } } #endregion
6.nameof表达式
#region 6.nameof表达式 (nameof expressions) { /*比如我们平时喜欢写字符串的形式,如果项目越来越大,后期突然哪个不用了, * 使用字符串的形式维护起来就会很麻烦,用nameof就可以很好的解决,最重要的是不会影响性能!*/ WriteLine(nameof(people)); WriteLine(nameof(people.Name)); } #endregion
7.在属性/方法里使用Lambda表达式
/// <summary> /// C#6新语法:在属性/方法里使用Lambda表达式(Expression bodies on property-like function members) /// </summary> public string NameFormat => string.Format("姓名:{0}", "NameFormat"); /// <summary> /// C#6新语法:在属性/方法里使用Lambda表达式(Expression bodies on property-like function members) /// </summary> public void Print() => WriteLine(NameFormat);
#region 7.在属性/方法里使用Lambda表达式(Expression bodies on property-like function members) { people.Print(); } #endregion