C# 6新特性
静态导入
// 静态的using声明允许调用静态方法时不使用类名
// C# 5
using System;
Console.WriteLine("C# 5");
// C# 6
using static System.Console;
WriteLine("C# 6");
表达式体方法
// C# 5
public bool IsSquare(Rectangle rect)
{
return rect.Width == rect.Height;
}
// C# 6
public bool IsSquare(Rectangle rect) => rect.Width == rect.Height;
表达式体属性
// C# 5
public string FullName
{
get
{
return FirstName + " " + LastName;
}
}
// C# 6
public string FullName => FirstName + " " + LastName;
自动实现的属性初始化器
// C# 5
public class Person
{
public Person()
{
Age = 24;
}
public int Age { get; set; }
}
// C# 6
public class Person
{
public int Age { get; set; } = 24;
}
自动属性-只读
// C# 5
private readonly int _bookId;
public BookId
{
get
{
return _bookId;
}
}
// C# 6
private readonly int _bookId;
public BookId { get; }
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(o));
}
}
空值传播运算符
// C# 5
int? age = p == null ? null : p.Age;
// C# 6
int? age = p?.Age;
字符串内插
// C# 5
public override string ToString()
{
return string.Format("{0},{1}", Title, Publisher);
}
// C# 6
public override string ToString() => $"{Title}{Publisher}";
字典初始化
// C# 5
var dic = new Dictionary<int, string>();
dic.Add(3, "three");
dic.Add(7, "seven");
// C# 6
var dic = new Dictionary<int, string>()
{
[3] = "three",
[7] = "seven"
};
异常过滤器
// C# 5
try
{
//
}
catch (MyException ex)
{
if (ex.ErrorCode != 405) throw;
}
// C# 6
try
{
//
}
catch (MyException ex) when (ex.ErrorCode == 405)
{
//
}
catch中的await
// C# 5
bool hasError = false;
string errorMsg = null;
try
{
//
}
catch (MyException ex)
{
hasError = true;
errorMsg = ex.Message;
}
if (hasError)
{
await new MessageDialog().ShowAsync(errorMsg);
}
// C# 6
try
{
//
}
catch (MyException ex)
{
await new MessageDialog().ShowAsync(ex.Message);
}
本文系作者 @jiang 原创发布在 IT梦。未经许可,禁止转载。