C# 3.0新特性介紹(對象和集合初始化)
作者:云飛揚(yáng)
本文繼續(xù)講解C#3.0新特性中的對象和集合初始化,并且舉例說明,希望對大家有所幫助。
在C# 3.0里,對象和集合初始化更容易了。繼續(xù)C# 3.0新特性之自動(dòng)屬性,現(xiàn)在看看如何對象和集合初始化
用《C# 3.0新特性(自動(dòng)屬性)》中的Point類
- public class Point
- {
- public int X { get; set; }
- public int Y { get; set; }
- }
對象類初始化可以這樣定義了
- Point p = new Point { X = 3, Y = 99 };
如果是集合初始化,主要繼承了System.Collections.Generic.IEnumerable< T> ,并且有個(gè)公共方法Add可以進(jìn)行初始化集合初始化
集合初始化例子具體如下
- List< Point> Square = new List< Point>
- {
- new Point { X=0, Y=5 },
- new Point { X=5, Y=5 },
- new Point { X=5, Y=0 },
- new Point { X=0, Y=0 }
- };
完整的例子源碼
- class Program
- {
- static List< Customer> CreateCustomers()
- {
- return new List< Customer>
- {
- new Customer(1) { Name = “Alex Roland”, City = “Berlin” },
- new Customer(2) { Name = “Oliver Cox”, City = “Marseille” },
- new Customer(3) { Name = “Maurice Taylor”, City = “London” },
- new Customer(4) { Name = “Phil Gibbins”, City = “London” },
- new Customer(5) { Name = “Tony Madigan”, City = “Torino” },
- new Customer(6) { Name = “Elizabeth A. Andersen”, City = “Portland” },
- new Customer(7) { Name = “Justin Thorp”, City = “London” },
- new Customer(8) { Name = “Bryn Paul Dunton”, City = “Portland” }
- };
- }
- static void Main(string[] args)
- {
- List< Customer> customers = CreateCustomers();
- Console.WriteLine(”Customers:\n”);
- foreach (Customer c in customers)
- Console.WriteLine(c);
- }
C# 3.0新特性中的對象和集合初始化就給大家介紹到這里。
【編輯推薦】
責(zé)任編輯:book05
來源:
ajaxcn