對象說明

public class Person { public int Age{get; set;} public string Name{get; set;} List<Person> friends = new List<Person>(); public List<Person> Friends {get{ return friends;} } Location home = new Location(); public Location Home{ get {return home;}} public Person(){} public Person(string name) { Name = name; } } public class Location { public string Country {get; set;} public string Town {get; set;} }
--------------------------
初始化
Person tom1 = new Person(); tom1.Age=10; tom1.Name="Tom"; Person tom2 = new Person("Tom"); tom2.Age=10;
這是最典型的兩種對象初始化的表達式。一種使用無參構造函數,一種使用有參構造函數。
對象初始化加上屬性賦值的多語句能用一條語句寫出來嗎?
可以。對象初始化表達式
Person tom3 = new Person(){ Name="Tom",Age=10}; Person tom4 = new Person("Tom"){Age=10}; person tom5 = new Person{Name="Tom",Age=10};
一行代碼實現了多行代碼的操作,用的是表達式,可以干很多事情的。
Person[] family = new Person[] { new Person{Name="1",Age=1}, new Person{Name="2",Age=2}, new Person{Name="3",Age=3}, new Person{Name="4",Age=4} };
嵌套對象的初始化
Person tom = new Person { Name="Tom", Age = 10, Home = {Town = "a" , Country = "b"}, Friends = { new Person{Name="a",Age=10}, new Person { Name="b", Age = 10, Home= { Town = "b", Country = "c" } } } }