在C# 3.0里,对象和集合初始化更容易了。继续C# 3.0新特性之自动属性,现在看看如何对象和集合初始化
用《C# 3.0新特性(自动属性)》中的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> ,并且有个公共方法Add可以进行初始化集合初始化
集合初始化例子具体如下
- 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新特性中的对象和集合初始化就给大家介绍到这里。
【编辑推荐】