一、构造器的声明于调用
构造器的声明:
class TestConstruct
{
public TestConstruct(string name)
{
Name = name;
}
public string Name { get; set; }
public int Age { get; set; } = 100;
}
构造器的调用:
TestConstruct tc = new TestConstruct(“小李”);
二、默认构造器
如果一个类不显示的声明构造器,则编译器在编译器自动添加一个,如下:
class TestConstruct
{
public TestConstruct()
{
}
public string Name { get; set; }
public int Age { get; set; } = 100;
}
当然我们也可以显示的声明一个不获取参数的构造器,当我们显示声明了构造器,系统默认的构造器就会被替换掉。
三、对象初始化器(c#3.0后支持)
类的声明
class TestConstruct
{
public TestConstruct(string name)
{
this.Name = name;
}
public string Name { get; set; }
public int Age { get; set; } = 100;
}
调用
TestConstruct tc = new TestConstruct("小李") { Age = 200 };
四、集合初始化器
List<TestConstruct> testConstructs = new List<TestConstruct>() { new TestConstruct("小陈"), new TestConstruct("小宋") };
为集合赋初值
五、构造器的重载
class TestConstruct
{
public TestConstruct(string name,double height=180)//height为构造器的可选参数
{
this.Name = name;
this.Height = height;
}
public TestConstruct (double height)
{
this.Height = height;
}
public string Name { get; set; }
public int Age { get; set; } = 100;
public double Height { get; set; }
}
上述有两个构造器,一个构造器只有一个参数,另一个构造器有两个构造器有两个参数,并且给两个参数的构造器提供了可选参数,也就是给height赋初值180,这样做的好处是,省略了一个构造器的重载,这个构造器就是只传递name参数的构造器,有了可选参数,我们就可以不用给height赋初值了,只是给name传递一个值就好了,所以要尽量的使用可选参数而不是使用构造器重载。、
六、构造器链(通过构造器初始化器实现)
因为重载了多个构造器,会发现有重叠的代码,为了减少代码,比如上面提到的代码中,this.Height=height调用了两个,那么就可以使用构造器链来解决,如下:
1)参数多个调用参数少的,this关键字
class TestConstruct
{
public TestConstruct(double height)
{
this.Height = height;
}
public TestConstruct(string name,double height ):this(height)
{
this.Name = name;
}
public string Name { get; set; }
public int Age { get; set; } = 100;
public double Height { get; set; }
}
2)参数少的调用参数多的,使用初始化方法Initialize
class TestConstruct
{
public TestConstruct(double height)
{
string name = null;
Initialize(name, height);
}
public TestConstruct(string name, double height)
{
Initialize(name, height);
}
private void Initialize(string name, double height)
{
this.Name = name;
this.Height = height;
}
public string Name { get; set; }
public int Age { get; set; } = 100;
public double Height { get; set; }
}
}
3)参数少的调用参数多的,在this后面的参数列表中传入静态变量
class TestConstruct
{
public TestConstruct():this(staticName,staticHeight, staticAge)//注意这个this构造函数前面一定没有参数
{
}
public TestConstruct(string name, double height,int age)
{
this.Name = name;
this.Age = age;
this.Height = height;
}
private static string staticName { get; set; }
private static int staticAge { get; set; }
private static int staticHeight { get; set; }
public string Name { get; set; }
public int Age { get; set; } = 100;
public double Height { get; set; }
}
7、匿名类型
var patent1 = new
{
Name = "小王",
Age = 100
};
Console.WriteLine($"{patent1 .Name }{patent1 .Age}");
编译器在遇到匿名类型时,会自动生成一个CIL类,该类具有与匿名类型声明中的已经命名的值和属性类型对应的属性,对应代码中的string 类型的Name属性,和Int类型的Age属性,但是除非我们需要对一个不知道数据类型的集合进行高频率的查询,否则我们只是最好少使用隐式类型var,而是直接显示的指出类型。