C#杂记-简化的初始化

对象说明

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=;
tom1.Name="Tom"; Person tom2 = new Person("Tom");
tom2.Age=;

这是最典型的两种对象初始化的表达式。一种使用无参构造函数,一种使用有参构造函数。

对象初始化加上属性赋值的多语句能用一条语句写出来吗?

可以。对象初始化表达式

Person tom3 = new Person(){ Name="Tom",Age=};
Person tom4 = new Person("Tom"){Age=};
person tom5 = new Person{Name="Tom",Age=};

一行代码实现了多行代码的操作,用的是表达式,可以干很多事情的。

Person[] family = new Person[]
{
new Person{Name="",Age=},
new Person{Name="",Age=},
new Person{Name="",Age=},
new Person{Name="",Age=}
};

嵌套对象的初始化

Person tom = new Person
{
Name="Tom",
Age = ,
Home = {Town = "a" , Country = "b"},
Friends =
{
new Person{Name="a",Age=},
new Person
{
Name="b",
Age = ,
Home=
{
Town = "b",
Country = "c"
}
}
}
}
上一篇:ZOJ2975 伪数组压缩+组合数


下一篇:Mounting VMDK files in Linux