初始化器提供一种简洁的方式实例化和初始化对象。
- public class Curry {
- //自动属性
- public string MainIngredient { get; set; }
- public string Style { get; set; }
- public int Spiciness { get; set; }
- public Curry() { }//默认构造
- public Curry(string mainIngredient, string style, int spiciness) {
- MainIngredient = mainIngredient;
- Style = style;
- Spiciness = spiciness;
- }
- public Restaurant Origin { get;set; }
- }
- public class Restaurant
- {
- public Restaurant() { }
- public Restaurant(string name, string local, int rat)
- {
- Name = name;
- Location = local;
- Rating = rat;
- }
- public string Name { get; set; }
- public string Location { get; set; }
- public int Rating { get; set; }
- }
- public static void Main(string[] args){
- //对象初始化 常规方法(1)
- Curry tastyCurry = new Curry();
- tastyCurry.MainIngredient = "panir tikka";
- tastyCurry.Style = "jalfrezi";
- tastyCurry.Spiciness = 8;
- //常规方法(2)
- Curry curry = new Curry("hellokity", "kity", 8);
- //方法(3)初始化器的使用任意方式初始化类
- Curry currys = new Curry
- {
- MainIngredient = "bybe",
- Style = "8888",
- Spiciness = 8,
- //初始化器的嵌套使用 属性的初始化器
- Origin = new Restaurant
- {
- Name = "张三",
- Location = "西安",
- Rating = 5
- }
- };
- //集合初始化
- //List<Curry> curries = new List<Curry>();
- //curries.Add(new Curry("Chicken","Pathia",6));
- //curries.Add(new Curry("Vegetable","Korma",3));
- //curries.Add(new Curry("Prawn","Vindaloo",9));
- //集合初始化器的使用 可以替换上面的方式
- List<Curry> curries = new List<Curry> {
- new Curry{
- MainIngredient="Chicken",
- Style="Pathia",
- Spiciness=6
- },
- new Curry{
- MainIngredient="Vegetable",
- Style="Korma",
- Spiciness=3
- },
- new Curry{
- MainIngredient="Prawn",
- Style="Vindaloo",
- Spiciness=9
- }
- };
- //用Var关键字修饰对象数组的初始化,称为匿名对象数组。
- var currys = new[] {//匿名对象数组,var类型推理。
- new{MainIngredient = "bybe", Style = "bybyby",Spiciness = 8 },
- new{ MainIngredient = "haha", Style = "hahaha",Spiciness = 5},
- new{ MainIngredient = "haha", Style = "hahaha",Spiciness = 5}
- };
- }