参考:https://www.bilibili.com/video/BV1TJ411h7cZ?p=237
using System;
using System.Collections.Generic;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//初始化器可以分为对象的初始化器、集合的初始化器等
//后面创建了一个 StudentName 类
//1.类的初始化器的使用
//下面的语句调用了StudentName 类的初始化器,初始化器是如何工作的呢?它会先使用默认的构造函数创建类,然后进行初始化
var student1 = new StudentName { firstName = "zun", lastName = "wang" };
//上面的语句和var student1 = new StudentName() { firstName = "zun", lastName = "wang" };一个效果
//也可以如下面这样使用,其先调用有参数的构造函数,然后调用初始化器
var student2 = new StudentName("zun","wang") { ID = 1};
//使用初始化器的时候默认构造函数一定要是public 才可以被调用到
Console.WriteLine();
//2.匿名类的初始化器
//所谓匿名类如下创建
var student3 = new { Name = "wang", Age = 10 };
//里面有一个匿名类创建后给了student3变量,注意匿名类是只读的,不可以赋值
//这个匿名类在Linq语句中使用到了
//如使用join 语句的时候
//from j in Collection
//join f in Collection1 on j.Name equals f.Name
//select new {Name = j.Name, Age = f.Age, ID = j.ID}
//3.集合的初始化器
var studentList = new List<StudentName> {
new StudentName {firstName = "zhuang", lastName = "wang"},
new StudentName("mei", "zhang"){ID = 100}
};
Dictionary<int, StudentName> Dic = new Dictionary<int, StudentName>
{
{1, new StudentName("mei", "zhang"){ID = 100}},
{2, new StudentName("hua", "han"){ID = 101}}
};
Console.WriteLine(studentList[0].ToString());
Console.WriteLine(Dic[2].ToString());
Console.ReadKey();
}
}
//创建一个类
public class StudentName
{
public string firstName { get; set; }
public string lastName { get; set; }
public int ID { get; set; }
public StudentName()
{
}
public StudentName(string fName, string lName)
{
firstName = fName;
lastName = lName;
}
public override string ToString()
{
return firstName + "." + lastName;
}
}
}