对象说明
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
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" } } } }