本文主要是關注于LINQ——我認為是VS2008(.NET3.5)中最令人興奮的特性。LINQ使查詢成為了.NET中頭等的編程概念,被查詢的數據可以是XML(LINQ to XML)、Databases(LINQ to SQL、LINQ to Dataset、LINQ to Entities)和對象(LINQ to Objects)。LINQ也是可擴展的,允許你建立自定義的LINQ數據提供者(比如:LINQ to Amazon、LINQ to NHibernate、LINQ to LDAP)。
在這里我會討論C#3.0中的一些新的語言特性和改進,正是它們使得LINQ變得如此強大,讓你可以寫出這樣的代碼:
var result = from c in Customers where c.City == Boston" orderby c.LastName descending select new { c.FirstName, c.LastName, c.Address };
新的語言特性
I/ 自動屬性
public class Point { private int _x, _y; public int X { get { return _x; } set { _x = value; } } public int Y { get { return _y; } set { _y = value; } } }
public class Point { public int X { get; set; } public int Y { get; set; } }
(這個特性和LINQ還沒有關系)
II/ 局部變量類型
使用這個特性,聲明一個局部變量,它的具體類型是通過初始化表達式來推斷。這點是通過var關鍵詞完成的(這個使用腳本語言的人應該很熟悉,但它們實際上是有很大區別的)。我們可以寫出如下的代碼:
var num = 50; var str = "simple string"; var obj = new myType(); var numbers = new int[] {1,2,3}; var dic = new Dictionary<int,myType>();
int num = 50; string str = "simple string"; myType obj = new myType(); int[] numbers = new int[] {1,2,3}; Dictionary<int,myType> dic = new Dictionary<int,myType>();
III/ 對象初始化和集合初始化
我們繼續使用上面的Point類。假設我們想要這個類的一個實例,我們會建立對象并設置它的屬性,代碼會是這樣子的:
Point p = new Point(); p.X = 0; p.Y = 0;
文章來源于領測軟件測試網 http://www.kjueaiud.com/