书上定义:初始化器(C#3.0以后新增内容)为对象、集合以及泛型集合的实例化和初始化提供一种更加简洁的代码形式。
其实,我们在变量声明时,就可选初始化器
变量声明:
有效的修饰符组合 (opt) + 类型 + 变量名 + 初始化器(opt), (opt表示可选),比如:
int a = 1;
public static int b = 2;
上面两个变量声明中,其中 = 1和 = 2这部分就是初始化器,声明变量的同时就给变量赋值。 如果不用初始化器则可以表示为:
int a;
a = 1;
在实例化对象时,使用初始化器不需要定义构造函数(但在初始化之前就自动调用了无参构造函数)
class Program
{
static void Main(string[] args)
{
Student stu = new Student { Name = "xxx", Id = 101 };
}
}
class Student
{
public string Name { get; set; }
public int Id { get; set; }
}
还有一种是集合初始化器
class Program
{
static void Main(string[] args)
{
ArrayList stuList = new ArrayList()
{
new Student { Name = "xxx", Id = 101 },
new Student { Name = "xxy", Id = 102 },
new Student { Name = "xxz", Id = 103 }
};
}
}
class Student
{
public string Name { get; set; }
public int Id { get; set; }
}
(由于本人也正在学习,如有错误请指出,谢谢!)