初始化器

1. 对象初始化器

若定义匿名类型,则必须使用对象初始值设定项

//声明一个 StudentName 显示调用2参构造函数 
StudentName student1 = new StudentName("Craig", "Playstead");

//声明一个 StudentName对象初始化器,在声明中触发默认构造器,而不是2参的构造器
StudentName student2 = new StudentName
{
    FirstName = "Craig",
    LastName = "Playstead",
};
//声明一个 StudentName对象初始化器,不需要相应的构造函数,只有默认构造器来初始化对象
StudentName student3 = new StudentName
{
    ID = 183
};

//没有相应的构造函数
StudentName student4 = new StudentName
{
    FirstName = "Craig",
    LastName = "Playstead",
    ID = 116
};
//或者
StudentName student5 = new StudentName(){FirstName = "Craig", LastName = "Playstead",};
StudentName student6 = new StudentName("Craig", "Playstead"){ ID = 183 };

public class StudentName
{
// 默认构造函数 ,在对象初始化器初始化时触发
// 如果类中自定义了带参数的构造函数,编译不会生成默认的构造函数
// 如果没有默认的构造函数,则使用对象初始化时就会报错:没有实现无参的构造函数
// 更改public 为 private. 用对象初始化器会失败
public StudentName() { }

public StudentName(string first, string last)
{
FirstName = first;
LastName = last;
}

public string FirstName { get; set; }
public string LastName { get; set; }
public int ID { get; set; }

public override string ToString()
{
return FirstName + " " + ID;
}
}

 

2.集合初始化器

集合初始值设定项是一系列由逗号分隔的对象初始值设定项。

List<StudentName> students = new List<StudentName>()
{
  new StudentName {FirstName="Craig", LastName="Playstead", ID=116},
  new StudentName {FirstName="Shu", LastName="Ito", ID=112},
  new StudentName {FirstName="Gretchen", LastName="Rivas", ID=113},
  new StudentName {FirstName="Rajesh", LastName="Rotti", ID=114}
};
//或者
List<StudentName> students = new List<StudentName>
{
  new StudentName {FirstName="Craig", LastName="Playstead", ID=116},
  new StudentName {FirstName="Shu", LastName="Ito", ID=112},
  new StudentName {FirstName="Gretchen", LastName="Rivas", ID=113},
  new StudentName {FirstName="Rajesh", LastName="Rotti", ID=114}
};

3.匿名类型

//匿名类
var person = new { Name = "learning hard", Age = 25 };
// 定义匿名类型数组
var personcollection = new[] 
{
    new {Name ="Tom",Age=30},
    new {Name ="Lily", Age=22},
    new {Name ="Jerry",Age =32},    
};

 

posted @ 2016-06-14 19:14  楊柳  阅读(215)  评论(0编辑  收藏  举报