假设我有一个基类'Person'和3个派生类,'Student','Teacher'和'Administrator'。
在Web应用程序中,在客户端创建新人,在服务器端,创建所需子类的最有效方法是什么,而不必为每个子类重复所有基类属性。下面的示例我不得不重复每个子类的Name,DOB和Address属性。
void CreatePerson(someDto dto)
{
Person person;
if (dto.personType == 1)
{
person = new Student() { .. };
person.Name = "";
person.DOB = "";
person.Address = "";
}
else if (dto.personType == 2)
{
person = new Teacher() { .. };
person.Name = "";
person.DOB = "";
person.Address = "";
}
else if (dto.personType == 3)
{
person = new Administrator() { .. };
person.Name = "";
person.DOB = "";
person.Address = "";
}
// Do something with person..
}
答案 0 :(得分:5)
您可以移动if / else
中的常用内容 if (dto.personType == 1)
{
person = new Student() { .. };
}
else if (dto.personType == 2)
{
person = new Teacher() { .. };
}
else if (dto.personType == 3)
{
person = new Administrator() { .. };
}
person.Name = ""; // I believe these 3 properties will come from dto
person.DOB = "";
person.Address = "";