2008年11月3日星期一

New Features in C# 4.0

PDC 2008中,其中一段演講是介紹C# 4.0, 新版本的C#主要新增加4樣東西,其實改動不多是正常,別忘記現在的C#版本3.0,但亦是過渡版本的3.5,所以3.5->4.0改動不多亦是正常.
新特點有:
  • Dynamic lookup
  • Named and optional parameters
  • COM specific interop features
  • Variance

我比較關注Dynamic lookup和Named and optional parameters.
(以下例子是引用Microsoft的官方文件)
Dynamic lookup :
dynamic type -
透過dynamic type,可以call method並引進Parameter.
dynamic d = GetDynamicObject(…); 
d.M(7); //M=Method

另一個使用方法:
dynamic d = 7; // implicit conversion
int i = d; // assignment conversion , i = 7

感覺上好似C# 3.0的var keyword,但不同的是,如果第一行用var d = 7; compiler便會把d轉成int,而dynamic type此時依然是object type,而MS的文件都說:(The type dynamic can be thought of as a special version of the type object)

Dynamic operations -
不單止是Method
dynamic d = GetDynamicObject(…);
d.M(7); // calling methods
d.f = d.P; // getting and settings fields and properties
d[“one”] = d[“two”]; // getting and setting thorugh indexers
int i = d + 3; // calling operators
string s = d(5,7); // invoking as a delegate

Named and Optional Arguments :
VB一直有的東西,基本上大家不會陌生,只是C#在這個版本才容許.
public void M(int x, int y = 5, int z = 7)
{
....
}
M(1);

另外兩個新特性大家可以看看官方文件和PDC演講.
New Features in C# 4.0
Documentation / C# Dynamic Samples / IDynamic Object Example /Variance
http://code.msdn.microsoft.com/csharpfuture/Release/ProjectReleases.aspx?ReleaseId=1686
The Future of C#
http://channel9.msdn.com/pdc2008/TL16/

沒有留言:

發佈留言