使用对象初始值设定项可以在创建对象时向对象的任何可访问的字段或属性分配值,而无需显式调用构造函数。
/// <summary>
/// 对象和集合初始值设定项
/// </summary>
class CSharp30_Demo2
{
//对象初始化
private class Student
{
public string Name { get; set; }
public int Age { get; set; }
private string IdCard { get; set; }//private!!!
public override string ToString()
{
return "Student -> Name:" + Name + "\tAge:" + Age + "\tIdCard:" + IdCard + Environment.NewLine;
}
}
static public void CreateStudent()
{
Student stu = new Student { Name = "Jie", Age = 23 };
Console.WriteLine(stu.ToString());
}
//集合初始化
static List<Student> stuList = new List<Student>
{
new Student{Name="Name_1",Age=1},
new Student{Name="Name_2",Age=2}
};
static public void ShowStudentList()
{
foreach (var item in stuList)
{
Console.WriteLine(item.ToString());
}
}
}
/// 对象和集合初始值设定项
/// </summary>
class CSharp30_Demo2
{
//对象初始化
private class Student
{
public string Name { get; set; }
public int Age { get; set; }
private string IdCard { get; set; }//private!!!
public override string ToString()
{
return "Student -> Name:" + Name + "\tAge:" + Age + "\tIdCard:" + IdCard + Environment.NewLine;
}
}
static public void CreateStudent()
{
Student stu = new Student { Name = "Jie", Age = 23 };
Console.WriteLine(stu.ToString());
}
//集合初始化
static List<Student> stuList = new List<Student>
{
new Student{Name="Name_1",Age=1},
new Student{Name="Name_2",Age=2}
};
static public void ShowStudentList()
{
foreach (var item in stuList)
{
Console.WriteLine(item.ToString());
}
}
}