微软在Visual Studio 2015中更新C#语言到6.0,添加了很多很好的特性,以使C#语言继续跻身于最优秀语言之行列。下面通过一个例子快速感受一下C# 6.0的新特性,以下程序在VS2015正式版中测试通过。

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace CSharp6Research
{
//分数
public class Fraction
{
public int A { get; set; } public int B { get; set; } = ; public string Separator { get; } = "/"; public string SeparatorSpaces { get; } = string.Empty; public double Value => (double)A / B; public int this[int index] => index == ? A : B; public int this[string index] => index == "A" ? A : B; public override string ToString() => $"{A}{SeparatorSpaces}{Separator}{SeparatorSpaces}{B}"; public void Print() => Console.WriteLine(ToString()); public Fraction()
{ } public Fraction(int a, int b)
{
A = a;
B = b;
} public Fraction(int a, int b, string separatorSpaces) : this(a, b)
{
SeparatorSpaces = separatorSpaces;
if (string.IsNullOrEmpty(separatorSpaces))
{
throw new ArgumentNullException(nameof(separatorSpaces));
}
} public static readonly Dictionary<string, Fraction> CommonFractions =
new Dictionary<string, Fraction>
{
["zero"] = new Fraction(),
["one"] = new Fraction(, ),
["half"] = new Fraction(, ),
["quarter"] = new Fraction(, ),
["infinity"] = new Fraction(, ),
}; } public struct FractionStruct
{
public int A { get; }
public int B { get; }
public FractionStruct(int a, int b) { A = a; B = b; } public override string ToString() => $"{A}/{B}"; } class Program
{
static void Main(string[] args)
{
foreach (var f in Fraction.CommonFractions)
{
Console.WriteLine($"{f.Key} : {f.Value.Value}");
} var fraction = new Fraction(, , " ");
fraction.Print(); try
{
fraction = new Fraction(, , null);
}
catch (ArgumentNullException e) when (e.ParamName == "separatorSpaces")
{
Console.WriteLine("separatorSpaces can not be null");
} Fraction v;
Fraction.CommonFractions.TryGetValue("harf", out v);
v?.Print();
var a = v?.A;
Console.WriteLine(a == null);
var b = v?["B"];
Console.WriteLine(b == null);
Console.WriteLine(v?.ToString() == null); Console.WriteLine(new FractionStruct(, ).ToString());
Console.WriteLine(default(FractionStruct).ToString());
} }
}

运行结果如下,

zero : 0
one : 1
half : 0.5
quarter : 0.25
infinity : ∞
1 / 3
separatorSpaces can not be null
True
True
True
0/1
0/0

1. Auto-property initializers 自动属性初始化器

public int B { get ; set ; } = 1;

可以直接给自动属性赋值了,不需要写在构造函数中了。

2. Getter-only auto-properties 只读自动属性

public string SeparatorSpaces { get; } = string.Empty;

只读自动属性可以直接初始化,或者在构造函数中初始化。

3. Expression-bodied members 表达式体成员

public double Value => (double)A / B;

public int this[int index] => index == 0 ? A : B;

public void Print() => Console.WriteLine(ToString());

只读属性,只读索引器和方法都可以使用Lambda表达式作为Body。

4. String interpolation 字符串嵌入值

$"{A}{SeparatorSpaces}{Separator}{SeparatorSpaces}{B}";

字符串前加$,大括号中的表达式会在运行时计算值,并嵌入到字符串中。

5. nameof operator  nameof 运算符

throw new ArgumentNullException(nameof(separatorSpaces));

nameof会返回变量,参数或成员名。

这个很有用,原来写WPF中的ViewModel层的属性变化通知时,需要写字符串,或者使用MvvmLight等库中的帮助方法,可以传入获取属性的Lambda,但由于是在运行时解析,会有少许性能损失。现在好了,使用nameof运算符,既能保证重构安全和可读性,又能保证性能。

6. Dictionary initializer 字典初始化器

new Dictionary< string, Fraction>

{

["zero"] = new Fraction (),

["one"] = new Fraction (1, 1),

["half"] = new Fraction (1, 2),

["quarter"] = new Fraction (1, 4),

[ "infinity"] = new Fraction (1, 0),

};

现在字典可以用一种可读性更好的方法进行初始化,方括号包围的Key等于Value。

7. Exception filters 异常过滤器

catch (ArgumentNullException e) when (e.ParamName == "separatorSpaces")

{

Console.WriteLine("separatorSpaces can not be null");

}

设置进入catch块的条件。

8. Null propagation 空传播

v?.A

v?["B"]

v?.ToString()

对象为null时不调用属性,索引器,方法等,表达式返回null,和Swift中的用法相似。

9. Await in catch/finally catch和finally块中的await

例子如下,
Resource res = null;

try

{

res = await Resource.OpenAsync(…); // You could do this.

}

catch (ResourceException e)

{

await Resource.LogAsync(res, e); // Now you can do this …

}

finally

{

if (res != null) await res.CloseAsync(); // … and this.

}

最新文章

  1. iOS滤镜实现之Nashville【instagram】
  2. python unicode字节串转成中文问题
  3. Spark1.0新特性--&gt;Spark SQL
  4. Android将应用程序的崩溃信息如何保存到本地文件,并上传服务器
  5. SQL小技巧小知识
  6. SpringJDBC的简单应用
  7. CocoaPods 教程 转载
  8. js上三行下三行和添加多个附件
  9. 1029: [JSOI2007]建筑抢修 - BZOJ
  10. flex 调用WebService1(基于.net)
  11. qt获取本机网络信息
  12. No.2小白的HTML+CSS心得篇
  13. Asp.Net Core 中无法使用 ConfigurationManager.AppSettings
  14. Loadrunner Http接口Get/Post方法性能测试脚本解析
  15. Codeforces Round #542 C. Connect 搜索
  16. ubuntu12.04安装squid
  17. Egret容器的鼠标默认事件
  18. uboot的配置及编译
  19. [Python 网络编程] TCP Client (四)
  20. BNUOJ 52517 Another Server

热门文章

  1. bzoj1215 24点游戏
  2. C++ 函数特性_参数默认值
  3. Charles使用1
  4. CentOS 添加新硬件硬盘,扩展空间而无需重启虚拟机
  5. Hive 安装操作
  6. canvas设置阴影
  7. J2EE Filter中修改request内容
  8. 匹配ip等的正则式
  9. controller 允许跨域访问
  10. DBNavigator中把insert变为append