在写一些实体类的时候,我们往往在写构造方法的时候思考很长时间,除了一个无参构造器外还在想需要写几个构造器呢?哪些参数是需要初始化的。现在你再也不需要为这事烦恼了
C# 3.0为你提供了对象集合初始化器:
?
- /// <summary> /// 图书类
- /// </summary> public class Book
- { /// <summary>
- /// 图书名称 /// </summary>
- public string Title { get; set; } /// <summary>
- /// 单价 /// </summary>
- public float Price { get; set; } /// <summary>
- /// 作者 /// </summary>
- public string Author { get; set; } /// <summary>
- /// ISBN号 /// </summary>
- public string ISBN { get; set; } }
- //对象初始化器 Book book = new Book { Title="Inside COM",ISBN="123-456-789"};
现在你想初始化几个就初始化几个,不需要出现这种情况:
?
- public Book():this("") {
- } public Book(string title):this(title,0)
- { }
- public Book(string title, float price):this(title,price,"") {
- } public Book(string title, float price, string isbn)
- { this.Title = title;
- this.Price = price; this.ISBN = isbn;
- }
这一串的构造方法都是为了应付不同的初始化情况。
好了,来看看对象初始化器编译器在后面为我们做了些什么呢?










