2013-09-29 117 views
0

假设我有一个基类'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.. 
} 

回答

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 = ""; 
+0

感谢@Tilak。此外,在if块中设置派生类属性时,似乎我必须在大括号内完成此操作。我不能说'person = new Student(); person.studentProperty = ...'是否需要在卷曲的内部创建派生类属性? – Grant

+0

是的,[对象初始化程序](http://msdn.microsoft.com/en-us/library/vstudio/bb384062.aspx) – Tilak

+1

@ Grant实际上,这应该有效。 'x = new Type(){Property1 = value,Property2 = value}''是写'x = new Type(); x.Property1 =值; x.Property2 =值;'。两者都应以相同的方式工作。 – poke