您的位置:首页 > 编程语言 > C#

[转]简短介绍 C# 6 的新特性

2016-02-02 14:28 447 查看
原文地址:http://www.oschina.net/translate/briefly-exploring-csharp-new-features

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

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

那么让我们看看吧:

1. $ sign

使用它的目的是简化基于索引的字符串,仅此而已。它不是像现在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")
{
// this one will not execute.
}
catch (Exception ex) if (ex.Message == "Me")
{
// this one will execute
}


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))
{ }


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. 主构造器:

呼哈哈,主构造器将帮你消除在获取构造器参数并将其设置到类的域上,以支持后面的操作,这一痛苦. 这真的很有用。这个特性的主要目的是使用构造器参数进行初始化。当声明了主构造器时,所有其它的构造器都需要使用 :this() 来调用这个主构造器.

最后是下面的示例:

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


要注意主构造器的调用是在类的顶部.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: