2012-07-23 37 views
2

所以我得到了一个类人,它包含年龄,性别,姓名(和主键ID)。 后来我得到2子类人:函数与子类参数

Teacher(Class(French, math, english etc etc), Sick(boolean)) 

student(Class(French, math, english etc etc), Sick(boolean)) 
//so these 2 got the same 5 fields. 

现在我想打1层的方法,它可以创建他们的所有2。 (在实践中,甚至更多,但奥凯的问题,我会只使用这2个)

这是我想到的是:

public Person CreateNewPerson (int age, boolean sex, string name, int class, boolean sick, HELP HERE plz OFTYPE<TEACHER OR STUDENT>) 
{ 
    var Person1 = new Person { Age = age, Sex = sex, ....... }; 
    // but now to return it as the correct type I got no clue what todo 
    return (OFTYPE)Person1; // ofc this doesn t work but I hope you understand the problem here 
} 

希望有人能够帮助我在这里,是因为ATM我我为每个子类别制作了一个独立的CreateNewTeacherCreateNewStudent等等(我得到了他们中的5个^^)

在此先感谢!

PS:他们后来保存在不同的表,我并不想要他们都在同一个班,因为我知道我可以去,并添加喜欢的人一个布尔值:IsPersonChild,然后真或FLASE但呐^ h

+2

这功课吗? – albertjan 2012-07-23 08:49:23

+0

不是真的我正在研究一个项目,我们正在制作一个WCF服务,它从EF模型获取它的数据,但是我们在对象上使用了继承,所以他们从来没有使用过相同的ID。我这样做的项目是smartp1ck(dot)com。我只是写了这个快速解释我的问题,我必须承认它看起来像家庭作业^^。 – Maximc 2012-07-23 08:54:56

+0

只是想知道 - 你的课只是名称不同,或者他们有不同的行为? – 2012-07-23 09:14:47

回答

4

建议类设置:

public class Person 
{ 
    public string Name { get; set; } 
} 

public class Teacher : Person 
{ 
} 

public class Student : Person 
{ 
} 

public static class PersonFactory 
{ 
    public static T MakePerson<T>(string name) where T: Person, new() 
    { 
     T person = new T {Name = name}; 
     return person; 
    } 
} 

用法:

Teacher teacher = PersonFactory.MakePerson<Teacher>("Mrs. Smith"); 

Student student = PersonFactory.MakePerson<Student>("Johnny"); 
+1

注意:如果子类有不同的参数,使用工厂甚至可以处理if(typeof(T)== typeof(Teacher) ' – Liron 2012-07-23 09:02:23

+0

奥克感谢这解决了它,也需要与typeof的评论,因为我确实有不同的thx参数不同的子类,我会稍后在我的WCF服务thx – Maximc 2012-07-23 12:41:52

1

使用可以使用泛型这样的:

public T CreateNewPerson<T> (int age, boolean sex, string name, int class, boolean sick) where T : Person, new() 
{ 
    var Person1 = new T { Age = age, Sex = sex, ....... }; 
    return Person1; 
}