1.构造函数的作用
构造函数可在创建对象时指定必要的数据。
构造函数是“运行时”用来初始化对象实例的方法。
2.声明构造函数
定义构造函数需创建一个无返回类型的方法,方法名必须与类名完全一样;
当类没有显示定义构造函数时,编译器会在编译时自动添加一个无参构造函数,称为默认构造函数;
3.对象初始化器
对象初始化器用于初始化对象中所有可以访问的字段和属性,即当调用构造函数创建对象时,可在后面的一对大括号中添加成员初始化列表;
4.集合初始化器
集合初始化器语法与对象初始化器相似,用于在集合实例化期间向集合项赋值;
5.重载构造函数
通过构造函数参数数量和类型的区别,可以同时存在多个构造函数;
6.构造函数链:使用this调用另一个构造函数
即从一个构造函数中调用另一个构造函数,称为构造函数链,其实现方式是在构造函数用冒号且添加this关键字,再添加被调用构造函数的参数列表。
7.解构函数
解构函数做的事情与构造函数相反,即把封装好的项拆分为它的各个组成部分;
调用前要以内联形式声明out参数;
8.实例说明
using System;
using System.Collections.Generic;
namespace helloworld
{
class Program
{
static void Main(string[] args)
{
//调用构造函数
Employee employee = new Employee("xu", "shuai");
Employee employee1 = new Employee("11", "xu", "shuai");
//对象初始化
Employee employee2 = new Employee("xu", "shuai")
{
Salary = "not enough",
Id = "11"
};
//集合初始化器
List<Employee> employees = new List<Employee>()
{
new Employee("xu", "shuai"),
new Employee("xu", "shuai")
};
string id, firstName, lastName, salary;
employee2.Deconstruct(out id, out firstName, out lastName, out salary);
Console.WriteLine("{0} {1} {2}", firstName, lastName, salary);
Console.ReadLine();
}
}
public class Employee
{
private string _FirstName;
private string _LastName;
private string _Id;
private string _Salary;
public string FirstName { get; set; }
public string LastName { get; set; }
public string Id { get; set; }
public string Salary { get; set; }
public Employee(string firstName,string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public Employee(string id, string firstName, string lastName) : this(firstName, lastName)
{
Id = id;
}
public void Deconstruct(out string id,out string firstName,out string lastName,out string salary)
{
(id,firstName, lastName, salary) = (this.Id,this.FirstName, this.LastName, this.Salary);
}
}
}