Welcome

首页 / 软件开发 / C# / Orcas版C# 3.0新特性

Orcas版C# 3.0新特性2007-11-04Scott Guthrie自从微软March CTP版本的Visual Studio和.net Framework “Orcas”发布以来,许多博客作家都在考察和评论这一版本在run-time macros和code metrics等方面的新特性。

近日,微软ASP.NET 和Ajax开发部的头脑Scott Guthrie又在其博客中发布了C# 3.0的一些新特性。其文中重点提及的C#3.0的新特性如下:

Automatic properties——自动属性

Orcas 版的C#可以自动建立私有域和默认的get/set函数,而不必由用户手工声明私有域和手工建立get/set函数。如:我们使用以前的C#语言编程时,需要手工书写如下代码段:

以下是引用片段:

public class Person ...{
private string _firstName;
private string _lastName;
private int _age;
public string FirstName ...{
get ...{
return _firstName;
}set ...{
_firstName = value;
}
}
public string LastName ...{
get ...{
return _lastName;
}
set ...{
_lastName = value;
}
}
public int Age ...{
get ...{
return _age;
}
set ...{
_age = value;
}
}
}

使用Orcas 版的C#后我们可以利用其自动属性功能重写如上代码如下:

以下是引用片段:

public class Person ...{
public string FirstName ...{
get; set;
}
public string LastName ...{
get; set;
}
public int Age ...{
get; set;
}
}

或者为了更加简洁,我们可以减少空白区域,将代码紧凑如下:

以下是引用片段:

public class Person ...{
public string FirstName ...{
get; set;
}
public string LastName ...{
get; set;
}
public int Age ...{
get; set;
}
}

当C# “Orcas”编译器遇到一个如上所示的空白的get/set property implementation时,它将会在你的类中自动产生一个私有域,同时实现一个公共的getter and setter property implementation。这样做的好处是,从type-contract的角度看,类好像使用了上述第一段代码中的执行(implementation)。这就意味着,与公共领域不同,我们将来可以在property setter implementation中添加验证逻辑,而不需要改变任何与类相关的外部组件。