几周前我在不同的地方读到了有关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. 主构造器:
呼哈哈,主构造器将帮你消除在获取构造器参数并将其设置到类的域上,以支持后面的操作,这一痛苦. 这真的很有用。这个特性的主要目的是使用构造器参数进行初始化。当声明了主构造器时,所有其它的构造器都需要使用 :this() 来调用这个主构造器.
最后是下面的示例:
//this is the primary constructor:
class person(string firstname, string lastname)
{
public string firstname { get; set; } = firstname;
public string lastname { get; } = lastname;
}
要注意主构造器的调用是在类的顶部.