初始化器

1. 對象初始化器數組

若定義匿名類型,則必須使用對象初始值設定項ide

//聲明一個 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;
}spa

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

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

 

2.集合初始化器blog

集合初始值設定項是一系列由逗號分隔的對象初始值設定項。get

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.匿名類型string

//匿名類
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},    
};
相關文章
相關標籤/搜索