现在的位置: 首页 > 综合 > 正文

瞄了一眼C#3.0

2012年05月26日 ⁄ 综合 ⁄ 共 2347字 ⁄ 字号 评论关闭
起先是想看一下Anders的一个访谈,关于LINQ的.听完访谈后,看到有Dan Fernandez(Visual C#的Product Manager)的一篇关于LINQ文章的链接,跑了进去,紧接着瞄了一样C#3.0的Spec.估计在MS内部已经差不多整出来就等发布了.Anders那些关于LINQ的演示实在太cool了.
LINQ的MS官方定义如下:
LINQ stands for Language INtegrated Query and in a nutshell, it makes query and set operations, like SQL statements first class citizens in .NET languages like C# and VB. 
LINQ的意思就是整合了查询的语言,是SQL语句在.NET中语言中称为一等公民.当然这个语言不仅仅是C#,是所有.NET Language.当然还是必须躺在.NET FrameWork上,这也是老盖的目的啊,把程序员绑在MS上,下午我还在打趣,要是MS垮了,俺们的日子可咋过啊.
废话少说,摘几段代码爽一下:
using System;

using System.Query;

using Danielfe;

 

class Program

{

    
static void Main(string[] args)

    
{

        
string[] aBunchOfWords = {"One","Two""Hello"

  
"World""Four""Five"}
;

     

        var result 
=    

            from s 
in aBunchOfWords // query the string array 

            where s.Length 
== 5     // for all words with length = 5

            select s;               
// and return the string

        

        
//PrintToConsole is an Extension method that prints the value

        result.Print();

    }


}


这个编辑器还是C#1.1的,认不出C#3.0的关键字var,from,where,select.上面一段代码的作用是从一个数组中选出长度为5的字符串然后打印.
那么如何从数据库中查询那?下面这段代码是从NorthWind数据库的客户表(Customers)查出合约名称(ContactName)长度等于5的客户,然后打印.是不是很酷?不知道C#3.0将来会做成什么样子,不过单纯从这段代码来看的话,db.GetTable<Customs>()应该是把数据从数据库中一次性捞到内存中,然后用where过滤.不过这样的效率实在令人担忧,有几百万个客户,再大的内存也受不了.当然这只是从只言片语的代码中看,C#3.0肯定会对效率有比较完美的solution,Anders一定会做到.

using System;

using System.Query;

using Danielfe;

using System.Data.DLinq; //DLinq is LINQ for Databases

using nwind; //Custom namespace that is tool generated 

 

class Program

{

    
static void Main(string[] args)

    
{

        Northwind db 
= new Northwind("Data Source=(local);Initial Catalog=Northwind;Integrated Security=True");   

        Table
<Customers> allCustomers = db.GetTable<Customers>();

 

        var result 
= 

                from c 
in allCustomers

                where c.ContactTitle.Length 
== 5

                select c.ContactName;

 

        result.Print();   

    }


}


更多的LINQ代码示例查看101LINQSamples
我们知道C#2.0在C#1.1的基础上增加了Generics,Anonymous Methods,Iterators和Partial Types.C#3.0会增加什么特性那?看了一下C#3.0的SPEC,新增加的特性如下:
1.Implicitly typed local variables---var,跟JavaScript中的var类似,允许通过初始值来确定变量的类型.
2.Extension methods.允许通过添加附加方法的方式扩展已有的类型来构造新的类型.
3.Lambda expressions .是匿名方法的演化,提供增强的类型推断并增加到委托和表达式树的转化.
4.Object initializers.对象的构造和初始化
5.Anonymous types
6.Implicitly typed arrays
7.Query expressions
8.Expression trees
长达26页的Spec对上述八个新的或者增强的特性进行了详细的描述,C#有26章了.
C#3.0 SPEC的下载

抱歉!评论已关闭.