C# 语言新特性 —— C# 6

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);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值