本文的内容包括引入C#6.0中的新的语言特性有哪些. 还有已经被引入的代码名称为 “Roslyn”新编译器. 编译器是开放源码的,并且可以从 codeplex 网站的这个地址下载到源代码: https://roslyn.codeplex.com/. C# 6.0 中的新特性我们可以对这些新特性一个一个的进行讨论,而首先要列出 C# 6.0 中这些特性的一个清单
1. 自动的属性初始化器Auto Property initialzier之前的方式初始化一个自动属性Auto Property的唯一方式,就是去实现一个明确的构造器,在里面对属性值进行设置.
有了这个特性之后的方式使用 C# 6 自动实现的带有初始值的属性可以不用编写构造器就能被初始化. 我们可以用下面的代码简化上面的示例:
|
2. 主构造器我们使用构造器主要是来初始化里面的值.(接受参数值并将这些参数值赋值给实体属性). 之前的方式
有了这个特性之后的方式
在 C# 6 中, 主构造器为我们提供了使用参数定义构造器的一个简短语法. 每个类只可以有一个主构造器. 如果你观察上面的示例,会发现我们将参数初始化移动到了类名的旁边. 你可能会得到下面这样的错误“Feature ‘primary constructor’ is only available in ‘experimental’ language version.”(主构造器特性只在实验性质的语言版本中可用), 为了解决这个问题,我们需要编辑 SolutionName.csproj 文件,来规避这个错误 . 你所要做的就是在 WarningTag 后面添加额外的设置
‘主构造器’只在‘实验’性质的语言版本中可用 |
3. 字典初始化器之前的方式编写一个字典初始化器的老办法如下
有了这个特性之后的方式我们可以像数组里使用方括号的方式那样定义一个字典初始化器
4. 声明表达式之前的方式
有了这个特性之后的方式在 C# 6 中你可以在表达式的中间声明一个本地变量. 使用声明表达式我们还可以在if表达式和各种循环表达式中声明变量
5. 静态的 Using之前的方式对于你的静态成员而言,没必要为了调用一个方法而去弄一个对象实例. 你会使用下面的语法
之后的方式在 C# 6 中,你不用类名就能使用 静态成员 . 你可以在命名空间中引入静态类. 如果你看了下面这个实例,就会看到我们将静态的Console类移动到了命名空间中
|
6. catch块里面的await
C# 6 之前catch和finally块中是不能用 await 关键词的. 在 C# 6 中,我们终于可以再这两个地方使用await了.
7. 异常过滤器异常过滤器可以让你在catch块执行之前先进行一个 if 条件判断. 看看这个发生了一个异常的示例,现在我们想要先判断里面的Exception是否为null,然后再执行catch块
8. 用于检查NULL值的条件访问操作符?.看看这个实例,我们基于UserID是否不为null这个条件判断来提取一个UserRanking. 之前的方式
有了这个特性之后方式
C# 6.0中的新特性 第一次出现在 Venkat Baggu 博客 上. |
|
原文地址:http://www.oschina.net/translate/new-features-in-csharp?cmp