请解释一下“:this()”是指。我可以使用“base”而不是它。 当我将光标移动到“this”时,它会显示另一个构造函数。 或者当我用“base”替换它时,它会出现这样的错误:“对象不包含带有1个参数的构造函数”。
class Employee { private string name; private string surname; private DateTime birthday; private double height; private double salary; public string Name { get { return name; } set { if (name != value) { name = value; } } } public string Surname { get { return surname; } set { if (surname != value) { surname = value; } } } public DateTime Birthday { get { return birthday; } set { if (birthday != value) { birthday = value; } } } public double Height { get { return height; } set { if (height != value) { height = value; } } } public double Salary { get { return salary; } set { if (salary != value) { salary = value; } } } public string Full { get { return name + " " + surname; } } public Employee() { name = "Mina"; surname = "Babayeva"; birthday = DateTime.Now.AddYears(-19); height=175; salary = 3500; } public Employee(string name, string surname, DateTime birthday, double height, double salary) : this( name, surname) { this.birthday = birthday; this.height = height; this.salary = salary; } public Employee(string name) : this() { this.name = name; } public Employee(string name, string surname) : this(name) { this.surname = surname; } public void Print() { Console.WriteLine("Name is {0}\nSurname is {1}\nHeight is {2}\nBirthday is {3}\nSalary is {4}", this.Name, this.Surname, this.Height, this.Birthday.ToString("dd/MM/yyyy"), this.Salary); } //////////////////////////////// Employee a = new Employee(); Employee b = new Employee("Adil", "Babayev"); Employee c = new Employee("Zumrud","Babayeva",DateTime.Now.AddYears(-52),167,1000000); Employee e = new Employee("Hanna"); a.Print(); Console.WriteLine(); b.Print(); Console.WriteLine(); c.Print(); Console.WriteLine(); e.Print(); Console.WriteLine();
答案 0 :(得分:0)
在此上下文中,this
引用当前类的构造函数。 base
指的是基类/继承类的构造函数。所以不,它们不可互换。
答案 1 :(得分:0)
无论何时为类创建构造函数,实际上都是将对象创建为对象的单个副本。 this关键字就是那个实例。
示例Apple类:Orange {}
公共Apple() :这个() {} 这个。是对Apple实例的引用。在类构造函数上调用base时,您正在调用派生类构造函数。 公共Apple() :base(){}
会返回Orange Class Constructor,而不是Apple! 两者之间的巨大差异!!
请查看C#Constructor Chaining。
MSDN有关于你的任务的很好的例子和文件。
祝你好运我的朋友
亲切的问候。