C# 3.0新特性之对象和集合初始化
2009年8月18日 云飞扬 发表评论 阅读评论
-
在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);
}
本文来自: 本站内容欢迎转载,但是禁止去掉本文链接(转载无妨,去掉链接可耻!):http://www.ajaxcn.net/archives/175