Предположим, у вас есть класс Employee, как указано ниже, который имеет 3 конструктора.
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Qualification { get; set; }
public string MiddleName { get; set; }
public Employee(string firstName, string lastName)
{
FirstName= firstName;
LastName= lastName;
Qualification= "N/A";
MiddleName= string.Empty;
}
public Employee(string firstName, string lastName, string qualification)
{
FirstName= firstName;
LastName= lastName;
Qualification= qualification;
MiddleName= string.Empty;
}
public Employee(string firstName, string lastName, string qualification,
string middleName)
{
FirstName= firstName;
LastName= lastName;
Qualification= qualification;
MiddleName= middleName
}
}
В C # 4.0 вам нужно будет создать один конструктор, который заменит все 3 конструктора.
public class Employee
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Qualification { get; set; }
public string MiddleName { get; set; }
public Employee(string firstName, string lastName,
string qualification = "N/A", string middleName = "")
{
FirstName= firstName;
LastName= lastName;
Qualification= qualification;
MiddleName = middleName;
}
}
Этот конструктор можно вызывать следующими способами.
Employee emp = new Employee("Adil", "Mughal");
Employee emp = new Employee("Adil", "Mughal", middleName: "Ahmed");
Employee emp = new Employee("Adil", qualification:"BS");
Employee emp = new Employee("ABC", lastName: "EFG", qualification: "BS");
Employee emp = new Employee("XYZ", middleName: "MNO");