C# 6新特性简单总结

  最近在看《C#高级编程 C# 6&.NET Core 1.0》,会做一些读书笔记,也算对知识的总结与沉淀了。

  1.静态的using声明

   静态的using声明允许调用静态方法时不使用类名:

1 // C# 5
2 using System;
3 
4 Console.WriteLine("C# 5");
5 
6 // C# 6
7 using static System.Console;
8 
9 WriteLine("C# 6");

  2.表达式体方法

  表达式体方法只包含一个可以用Lambda语法编写的语句:

1 // C# 5
2 public bool IsSquare(Rectangle rect)
3 {
4      return rect.Width == rect.Height;
5 }
6 
7 // C# 6
8 public bool IsSquare(Rectangle rect) => rect.Width == rect.Height;

  3.表达式体属性

  与表达式体方法类似,只有get存储器的单行属性可以用Lambda语法编写:

 1 // C# 5
 2 public string FullName
 3 {
 4     get
 5     {
 6         return FirstName + " " + LastName;
 7     }
 8 }  
 9 
10 // C# 6
11 public string FullName => FirstName + " " + LastName;      

  4.自动实现的属性初始化器

  自动实现的属性可以用属性初始化器来初始化:

 1 // C# 5
 2 public class Person
 3 {
 4     public Person()
 5     {
 6         Age = 24;
 7     }
 8     public int Age { get; set; }
 9 }
10 
11 // C# 6
12 public class Person
13 {
14     public int Age { get; set; } = 24;
15 }

  5.只读的自动属性

 1 // C# 5
 2 private readonly int _bookId;
 3 public BookId
 4 {
 5     get
 6     {
 7         return _bookId;
 8     }
 9 }
10 
11 // C# 6
12 private readonly int _bookId;
13 public BookId { get; }

  6.nameof运算符

  使用新的nameof运算符,可以访问字段名、属性名、方法名和类型名。这样,在重构时就不会遗漏名称的改变:

 1 // C# 5
 2 public void Method(object o)
 3 {
 4     if(o == null)
 5     {
 6         throw new ArgumentNullException("o");
 7     }
 8 }
 9 
10 // C# 6
11 public void Method(object o)
12 {
13     if(o == null)
14      {
15         throw new ArgumentNullException(nameof(o));
16     }
17 }

  7.空值传播运算符

  空值传播运算符简化了空值的检查:

1 // C# 5
2 int? age = p == null ? null : p.Age;
3 
4 // C# 6
5 int? age = p?.Age;

  8.字符串插值

  字符串插值删除了对string.Format的调用,它不在字符串中使用编号的格式占位符,占位符可以包含表达式:

1 // C# 5
2 public override string ToString()
3 {
4     return string.Format("{0},{1}", Title, Publisher);
5 }
6 
7 // C# 6
8 public override string ToString() => $"{Title}{Publisher}";

  9.字典初始化

 1 // C# 5
 2 var dic = new Dictionary<int, string>();
 3 dic.Add(3, "three");
 4 dic.Add(7, "seven");
 5 
 6 // C# 6
 7 var dic = new Dictionary<int, string>()
 8 {
 9     [3] = "three",
10     [7] = "seven"
11 };

  10.异常过滤器

  异常过滤器允许在捕获异常之前过滤它们:

 1 // C# 5
 2 try
 3 {
 4       //
 5 }
 6 catch (MyException ex)
 7 {
 8     if (ex.ErrorCode != 405) throw;
 9 }
10 
11 // C# 6
12 try
13 {
14       //
15 }
16 catch (MyException ex) when (ex.ErrorCode == 405)
17 {
18     //
19 }

  11.catch中的await

  await现在可以在catch子句中使用,C# 5需要一种变通方法:

 1 // C# 5
 2 bool hasError = false;
 3 string errorMsg = null;
 4 try
 5 {
 6     //    
 7 }
 8 catch (MyException ex)
 9 {
10     hasError = true;
11     errorMsg = ex.Message;
12 }
13 if (hasError)
14 {
15     await new MessageDialog().ShowAsync(errorMsg);
16 }
17 
18 // C# 6
19 try
20 {
21     //
22 }
23 catch (MyException ex)
24 {
25     await new MessageDialog().ShowAsync(ex.Message);
26 }

 

posted @ 2019-01-16 14:14  Zoe_yan  阅读(2805)  评论(0编辑  收藏  举报