简要探索 C# 6 的新特性






4.65/5 (78投票s)
简要探索 C# 6 的最重要的几个新特性
几周前,我阅读了关于 C# 6 中一些新特性的文章。我决定将它们收集起来,以便您可以在还没看过的时候一次性查看。其中一些可能不像预期的那么令人惊叹,但这就是现在的更新。
您可以通过下载 VS 2014 或从此处安装针对 Visual Studio 2013 的 Roslyn 包来获取它们。
更新
我会在 Roslyn 下载包中添加新项目,或者一旦它们从 Roslyn 下载包中删除就删除它们。
那么,让我们开始吧。
1. $ 符号
它的目的是简化基于字符串的索引,仅此而已。它不像 C# 当前的动态特性,因为它内部使用常规的索引功能。为了理解它,让我们考虑以下示例
var col = new Dictionary<string, string>()
{
// using inside the intializer
$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 关键字,无论如何现在可以使用了。这很棒,因为我们经常希望在 catch 块中执行 I/O 操作以记录异常原因,或者在 finally 块中执行类似的操作,并且它们需要异步。
try
{
DoSomething();
}
catch (Exception)
{
await LogService.LogAsync(ex);
}
4. 声明表达式
此功能允许您在表达式中间声明局部变量。就这么简单,但确实消除了一个痛苦。我过去做过很多 asp.net web form 项目,这是我每天都在编写的代码
long id;
if (!long.TryParse(Request.QureyString["Id"], out id))
{ }
可以改进为这样
if (!long.TryParse(Request.QureyString["Id"], out long id))
{ }
这种声明的范围规则与 C# 中的一般范围规则相同。
5. using 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;
}
请注意,主要构造函数的声明位于类的顶部。
8- 字典初始化器
有些人认为旧的初始化字典的方式很糟糕,所以 C# 团队决定让它更干净,感谢他们。这里有一个关于旧方式和新方式的例子
// the old way of initializing a dictionary Dictionary<string, string> oldWay = new Dictionary<string, string>() { { "Afghanistan", "Kabul" }, { "United States", "Washington" }, { "Some Country", "Some Capital city" } }; // new way of initializing a dictionary Dictionary<string, string> newWay = new Dictionary<string, string>() { // Look at this! ["Afghanistan"] = "Kabul", ["Iran"] = "Tehran", ["India"] = "Delhi" };