如何有效地创建派生类

Gra*_*ant 0 .net c# oop polymorphism inheritance

假设我有一个基类'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..
}
Run Code Online (Sandbox Code Playgroud)

Til*_*lak 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 = "";
Run Code Online (Sandbox Code Playgroud)