首页 > c# > 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);
        }

原创文章转载请注明出处:云飞扬IT的blog

本文链接: http://www.ajaxcn.net/archives/175

分类: c# 标签: ,
一键分享到:新浪微博分享  分享到网易微博    转贴到开心网  推荐到豆瓣  分享到QQ空间    RSS订阅
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.