CSharp3对象初始化程序

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace ConsoleApplication1
 8 {
 9     public class Location
10     {
11         public string Country { get; set; }
12         public string Town { get; set; }
13     }
14     public class Person
15     {
16         public int Age { get; set; }
17         public string Name { get; set; }
18         List<Person> friends = new List<Person>();
19         public List<Person> Friends { get { return friends; } }
20 
21         Location home = new Location();
22         public Location Home { get { return home; } }
23         public Person() { }
24         public Person(string name)
25         {
26             Name = name;
27         }
28     }
29     class Program
30     {
31         static void Main(string[] args)
32         {
33             Person tom = new Person  //调用无参数构造函数
34             {
35                 Name = "Tom",  //直接设置属性
36                 Age = 6,
37                 Home = { Town = "Reading", Country = "UK" }, //初始化嵌入对象
38                 Friends =
39                 {
40                     new Person { Name = "Alberto"},     //用更进一步的对象初始化器来初始化集合
41                     new Person ("Max"),
42                     new Person { Name = "Zak", Age = 4 },
43                     new Person ("Ben"),
44                     new Person("Alice")
45                     {
46                         Age = 6,
47                         Home = { Town = "Twyford", Country = "UK" }
48                     }
49                 }
50             };
51 
52 
53             Console.ReadKey();
54         }
55     }
56 }

 

posted @ 2014-04-28 09:17  海阔天空XM  阅读(939)  评论(0编辑  收藏  举报