简短介绍 C# 6 的新特性

jopen 10年前

几周前我在不同的地方读到了有关C#6的一些新特性。我就决定把它们都收集到一起,如果你还没有读过,就可以一次性把它们都过一遍。它们中的一些可能不会如预期那样神奇,但那也只是目前的更新。

你可以通过下载VS2014或者安装这里针对visual studio2013的Roslyn包来获取它们。

那么让我们看看吧:

1. $标识符

$的作用是简化字符串索引。它与C#中那些内部使用正则表达式匹配实现索引的动态特性不同。示例如下:

var col = new Dictionary<string, string>()              {                  $first = "Hassan"              };       //Assign value to member     //the old way:     col.$first = "Hassan";       //the new way:     col["first"] = "Hassan";

2. 异常过滤器

VB编译器中早已支持异常过滤器,现在C#也支持了。异常过滤器可以让开发人员针对某一条件创建一个catch块。只有当条件满足时catch块中的代码才会执行,这是我最喜欢的特性之一,示例如下:

try              {                  throw new Exception("Me");              }              catch (Exception ex) if (ex.Message == "You")

3. catch和finally块中await关键字

据我所知,没有人知道C# 5中catch和finally代码块内await关键字不可用的原因,无论何种写法它都是不可用的。这点很好因为开发人员经常想查看I/O操作日志,为了将捕捉到的异常信息记录到日志中,此时需要异步进行。

try              {                  DoSomething();              }              catch (Exception)              {                  await LogService.LogAsync(ex);              }

4. 声明表达式

这个特性允许开发人员在表达式中定义一个变量。这点很简单但很实用。过去我用asp.net做了许多的网站,下面是我常用的代码:

long id;  if (!long.TryParse(Request.QureyString["Id"], out id))  { }

优化后的代码:

if (!long.TryParse(Request.QureyString["Id"], out long id))  { }

这种声明方式中变量的作用域和C#使用一般方式声明变量的作用域是一样的。

5. Static的使用

这一特性允许你在一个using语句中指定一个特定的类型,此后这个类型的所有静态成员都能在后面的子句中使用了.

using System.Console;    namespace ConsoleApplication10  {      class Program      {          static void Main(string[] args)          {              //Use writeLine method of Console class              //Without specifying the class name              WriteLine("Hellow World");          }      }  }

6. 属性的自动初始化:

C# 6 自动舒适化属性就像是在声明位置的域。这里唯一需要知道的是这个初始化不会导致setter方法不会在内部被调用. 后台的域值是直接被设置的,下面是示例:

public class Person      {          // You can use this feature on both          //getter only and setter / getter only properties            public string FirstName { get; set; } = "Hassan";          public string LastName { get; } = "Hashemi";      }

7. Primary Constructor:

Woohooo, primary constructors will help destroy the pain of capturing values of constructor parameters to fields in the class for further operations. This is really useful. The main purpose for it is using constructor parameters for initialization. When declaring a primary constructor all other constructors must call the primary constructor using :this().

here is an example finally:

//this is the primary constructor:      class Person(string firstName, string lastName)      {          public string FirstName { get; set; } = firstName;          public string LastName  { get; } = lastName;      }

notice that declaration of primary constructor is at the top of the class.