public class Person { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } private int test01 = 25; internal int test02; }
class Program { static void Main(string[] args) { Person person = new Person { FirstName = "Scott", LastName = "Guthrie", test02 = 56, }; Console.WriteLine(person.test02); Console.WriteLine(person.Age); Console.ReadLine(); }
}
问题三:对象初始化器是否可以结合构造函数一起使用?
答案:可以参看如下代码就可以正常使用:
var cookie3 = new System.Net.Cookie("MyCookie", "Jose") { Comment = "a cookie" };
static void Main(string[] args) { var cookie = new System.Net.Cookie("MyCookie", "Jose") { Name = "test02", Comment = "a cookie" }; Console.WriteLine(cookie.Name); Console.ReadLine(); }
答案:
构造函数比初始化构造器更早被执行。
上述WriteLine 写出来的信息为:test02
集合初始化器(Collection Initializers) 的一些问题:
问题一:集合初始化构造器中是否可以构造集合的一项为空值?
答案:可以,参看下述代码。
问题二:集合初始化构造器是否可以初始化Hashtable ?
答案:可以。这时候相当于用了两个对象初始化构造器,参看下面代码:
public class Person { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } private int test01 = 25; internal int test02; }