C# 语言新特性 —— C# 6
一、静态引用(static using)
// C# 6 以前版本:
using System;
Console.WriteLine("Hello,world");
// C# 6
using static System.Console;
WriteLine("Hello world");
二、表达式方法体方法定义(Expression-Bodied Methods)
// C# 6 以前版本:
using System;
public void SayHi()
{
Console.WriteLine("Hi!");
}
// C# 6
using static System.Console;
public void SayHi() => WriteLine("Hi");
三、表达式方法体属性定义(Expression-Bodied Properties)
// C# 6 以前版本
public string FullName
{
get
{
return FirstName + " " + LastName;
}
}
// C# 6
public string FullName => FirstName + " " + LastName;
四、自动生成属性初始化器(Auto-Implemented Property Initializers)
// C# 6 以前版本
public class Person
{
public Person()
{
Age = 18;
}
public int Age { get;set; }
}
// C# 6
public class Person
{
public int Age { get;set; } = 18;
}
五、只读属性(Read-Only Auto Properties)
// C# 以前版本
private readonly string _name;
public string Name
{
get
{
return _name;
}
}
// C# 6
public string Name { get; }
六、nameof 操作符(nameof Operator)
nameof 操作符用于获取字段,属性,方法或类型的名称。
// C# 6 以前版本
public void Method(object o)
{
if(o == null) throw new ArguemntNullException("o");
Console.WriteLine("Object o is {0}",o);
}
// C# 6
public void Method(object o)
{
if(o == null) throw new ArguemntNullException(nameof(o));
Console.WriteLine($"Object o is {o}");
}
七、?. 运算符—— Null 扩展运算符(Null Propagation Operator)
public event EventHanlder<EventArgs> Click;
// C# 6 以前版本
int? age = person == null ? : null: person.Age;
var handler = Click;
if(handler != null)
{
handler(source,e);//触发事件
}
// C# 6
int? age = person?.Age;
handler?.Invoke(source,e);
八、字符串内插
// C# 6 以前版本
public override string ToString()
{
return Sting.Format("{0} {1}",FirstName,LastName);
}
// C# 6
public override string ToString() => $"{FirstName} {LastName}";
九、字典初始化器
// C# 6 以前版本
var dict = new Dictionary<int,string>
{
{1,"Tom"},
{2,"Perter"}
};
// C# 6
var dict = new Dictionary<int,string>()
{
[1] = "Tom",
[2] = "Perter"
};
十、异常过滤器(Exception Filters)
// C# 6 以前版本
try
{
//etc.
}
catch(Exception ex)
{
if(ex is IOException) throw;
//etc.
}
// C# 6
try
{
//etc.
}
catch(Exception ex) when (ex is IOException)
{
//etc.
}
十一、异步异常处理(Await in Catch)
// C# 6 以前版本
var hasError = false;
var errorMessage = null;
try
{
//etc.
}
catch(Execption ex)
{
hasError = true;
errorMessage = ex.Message;
}
if(hasError)
{
await new MessageDialog().showAsync(errorMessage);
}
// C# 6
try
{
//etc.
}
catch(Exception ex)
{
await new MessageDialog().ShowAsync(ex.Message);
}