具有子类参数的函数

时间:2012-07-23 08:45:36

标签: c# class inheritance

所以我得到了一个Class Person,它包含年龄,性别,姓名(以及主键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.

现在我想创建一个可以创建所有2个方法的方法。 (在实践中,对于我将使用这些问题的问题,甚至更多但是oke)

这就是我的想法:

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
}

希望有人能够在这里帮助我,因为我正在为我得到的每个子类制作一个单独的CreateNewTeacherCreateNewStudent等等。(我得到了其中的5个^^)

提前致谢!

PS:它们以后会保存在不同的表中,我不希望它们都在同一个类中,因为我知道我可以去添加类似布尔值的人:IsPersonChild然后是true或flase但是na ħ

2 个答案:

答案 0 :(得分: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 :(得分: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; 
}