C# 3.0 中对象初始化器,Object Initializers 和 集合初始化器
C# 3.0 中对象初始化器(Object Initializers) 和 集合初始化器(Collection Initializers) ,就是简化我们的代码,让本来几行才能写完的代码一行写完。这样在LINQ的使用中,我们才不会把一个LINQ表达式写的巨复杂无比。 由于我看到几篇讲 对象初始化器(Object Initializers)和集合初始化器(Collection Initializers) 的文章,都是一个简单的例子,一些稍稍特殊一点的场景的初始化赋值并没有涉及,所以我特整理这篇博客。 关于对象初始化器(Object Initializers) 的一些问题: 问题一: 对象初始化器允许只给部分值赋值么?即不给其中一些值赋值 答案:允许;参考后面的代码。 问题二:对象初始化器允许给internal 的成员赋值?(私有成员肯定不用想了,肯定不能赋值。) 答案:允许;参考下面的代码。 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" }; 我们在构造函数中给 Cookie 的名字和值赋了值,在初始化构造器中给 Comment 属性赋了值。 问题四:构造函数赋值和初始化构造器赋值那个最先被执行? 比如下述代码,结果是那个呢?? 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; } class Program { static void Main(string[] args) { List<Person> people = new List<Person>{ new Person { FirstName = "Scott", LastName = "Guthrie", Age = 32 }, new Person { FirstName = "Bill", LastName = "Gates", test02 = 85}, new Person { FirstName = "Susanne", Age = 32 }, null, }; Hashtable pp = new Hashtable { { 1, new Person { FirstName = "Scott", LastName = "Guthrie", Age = 32 } }, { 2, new Person { FirstName = "Bill", LastName = "Gates", test02 = 85} }, { 3, new Person { FirstName = "Susanne", Age = 32 } }, { 4, null }, }; Console.ReadLine(); } } 以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |