base()
默认情况下会调用它,但它可以用于其他目的,例如:
- base()` 方法用于将值传递给父类构造或
- 调用父类的无参数构造函数。
例如:
情况 1:如果父级具有参数化构造函数但没有默认或无参数构造函数。
class Person
{
private string FirstName;
private string LastName;
private string EmailAddress;
private DateTime DateOfBirth;
public Person(string firstName, string lastName, string emailAddress, DateTime dateOfBirth)
{
FirstName = firstName;
LastName = lastName;
EmailAddress = emailAddress;
DateOfBirth = dateOfBirth;
}
}
class Employee : Person
{
private double Salary { get; set; } = 0;
public Employee(string firstName, string lastName, string emailAddress, DateTime dateOfBirth,double salary)
:base(firstName,lastName,emailAddress,dateOfBirth)// used to pass value to parent constructor and it is mandatory if parent doesn't have the no-argument constructor.
{
Salary = salary;
}
}
情况 2:当父级具有多个构造函数以及默认构造函数时。
class Person
{
private string FirstName;
private string LastName;
private string EmailAddress;
private DateTime DateOfBirth;
public Person()
{
// some important intialization's to be done
}
public Person(string firstName, string lastName, string emailAddress, DateTime dateOfBirth)
{
FirstName = firstName;
LastName = lastName;
EmailAddress = emailAddress;
DateOfBirth = dateOfBirth;
}
}
class PermanentEmployee : Person
{
public double HRA { get; set; }
public double DA { get; set; }
public double Tax { get; set; }
public double NetPay { get; set; }
public double TotalPay { get; set; }
public PermanentEmployee(double hRA, double dA, double tax, double netPay, double totalPay) : base();
{
HRA = hRA;
DA = dA;
Tax = tax;
NetPay = netPay;
TotalPay = totalPay;
}
}
在这里,我们通过 base() 手动调用无参数构造函数来执行一些 intilizations 但不传递任何值。
希望这会帮助你。