还是记录一下吧,好记性不如烂笔头。
1、静态的 using 声明
静态的 using 声明允许条用方法时候不适用类名。
C# 5:
using System;
//etc
Console.WriteLine("Hello,World!");
C# 6:
using static System.Console;
//etc.
Writeline("Hello,World");
2、表达式体方法
表达式体方法只包括一个可以用 lambda语法编写语句:
C# 5:
public bool IsSquare(Rectangle rect)
{return rect.Height == rect.Width;
}
C# 6:
public bool IsSquare (Rectangle rect) => rect.Height == rect.Width;
3、表达式体属性
与表达式体方法类似,只有get存取器的单行属性可以用lambda语法编写:
C# 5
public string FullName
{get{return FirstName + "" + LastName;}
}
C# 6
public string FullName => FirstName + "" +LastName;
4、自动实现的属性初始化器
自动实现的属性可以用属性初始化器来初始化:
C# 5
public class Person
{public Person(){Age = 24;}public int Age { get;set;}
}
C# 6
public class Person
{public int Age {get;set;} = 42;
}
5、只读的自动属性
为了实现只读属性,C# 5 需要使用完整的属性语法:而在C# 6中,可以使用自动实现的属性:
C# 5
private readonly int _bookId;public BooKId
{get{ret _bookId;}
}
C# 6
public BookId {get;}
6、nameof 运算符
使用新的nameof运算符,可以访问字段名、属性名、方法名或者类型名。这样,在重构时,就不会遗漏名称的改变:
C# 5
public void Method( object o )
{if( o == null) throw new ArgumentNullException("o");
}
C# 6
public void Method (object o)
{if(o == null) throw new ArgumentNullException (nameof(0));
}
7、 空值传播运算符
空值传播运算符简化了空值的检查:
C# 5
int? age = p == null ? null : p.Age;
C# 6
int? age = p?.Age;
新语法也有触发事件的优点:
C# 5
var handler = Event;
if(handler != null)
{handler(source,e);
}
C# 6
handler?.Invoke(source,e);
8、字符串插值
字符串插值删除了对 string.Format的调用,它不在字符串中使用编号的格式占位符,占位符可以包含表达式:
C# 5
public override ToString()
{return string.Format("{0},{1}",Title,Publisher);
}
C# 6
public override ToString() => $"{Title} {Publisher}";
9、字典初始化器
字典现在可以用字典初始化器来初始化,类似于集合初始化器。
C# 5
var dict = new Dictionary<int , string>();
dict.Add(3,"three");
dict.Add(7,"seven");
C# 6
var dict = new Dictionary <int ,string>()
{[3] = "three",[7] = "seven"
}
10、异常过滤器
异常过滤器允许在捕获异常之前过滤他们。
C# 5
try
{//etc.
}
catch (MyException ex)
{if(ex.ErrorCode != 405) throw;
}
C# 6
try
{//etc.
}
catch (MyExctption ex) when (ex.ErrorCode == 405)
{//etc.
}
新语法的优势是,它不仅减少了代码额的长度,而且没有改变堆栈跟踪 -------在 C# 5 中会改变堆栈跟踪。
11、Catch 中的 await
await 现在可以在catch子句中使用。C# 5需要一种变通方法:
C# 5
bool hasError = false;
string errorMessage = null;
try
{//etc.
}
catch (MyException ex)
{hasError = true;errorMessage = ex.Message;
}
if(hasError)
{await new MessageDialog().ShowAsync(errorMessage);
}
C# 6
try
{//etc.
}
catch (MyException ex)
{await new MessageDialog().ShowAsync(ex.Message);
}