抽了点时间,熟悉一下3.0的新特性,发觉c#新特性及进步趋势是语言动态化(或者讲脚本化,也汲取了一些脚本语言的好特性),而内在是compiler做了更多的事情,而方便了程序员,几个新特性最终为Linq的实现服务(新特性是一层层叠加上去的,如class->delegate->lambda expression便是其一),而Linq则在ADO.NET Entity及其他查询中作用巨大。
主要参考自C# 3.0 Pocket Reference,未说到的细节到书中查看(google一下ebook)
1、Lambda Expressions:
类似于匿名方法,语法格式:
(parameters) => expression-or-statement-block
Compiler将为你编译出一个delegate,参数可以指定类型,可以指定return,如(int i)=>{return i*i;}
因此Framework lib中定义了两个常用的lambda expression,其实就是两个generic delegate,即Func和Action (Func的无返回版本)
delegate TResult Func <T, TResult>(T arg1) 等价于 (T arg1)=>(..return TResult)
Func<int,int> sqr = x => x * x;
Console.WriteLine (sqr(3)); // 9
2、Extension Methods:
不修改一个类型的定义,而为其增加方法,类型可以是接口(听起来挺强吧)
语法:将需增加的方法定义为一个static class的static method,第一参数指定扩展的类型并用this修饰
如:public static bool IsCapitalized (this string s)
使用:”hello”.IsCapitalized(),其实compile时compiler帮你改写成对static method IsCapitalized的调用,将”hello”作参数传入
public static T First<T> (this IEnumerable<T> sequence)
System.Linq.Enumerable类中便定义了n多扩展IEnumerable<>的方法
4、Anonymous Type:
语法:var dude = new { Name = "Bob", Age = 1 };
有脚本的感觉了吧,到现在才有,管谁的呐,好东西就应该拿过来
上述三样都是为下面这项服务的
5、Linq(Language
Integrated Query):
上述的三样+Query syntax基本就有了linq
LINQ lets you query any collection implementing IEnumerable<>, whether an array, list, XML DOM, or remote data source (such as a table in SQL Server). LINQ offers the benefits of both compile-time type checking and dynamic query composition.