c# - 带有子类参数的函数

标签 c# class inheritance

所以我得到了一个 Class Person,它包含年龄、性别、姓名(和主键 ID)。 然后我得到了 person 的 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:它们稍后保存在不同的表中,我不希望它们都在同一个类中,因为我知道我可以像 bool 值一样添加 person: IsPersonChild 然后 true 或flase但不h

最佳答案

建议的类(class)设置:

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");

关于c# - 带有子类参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11609141/

相关文章:

c# - 用于 Java 或 C# 或 vb.net 的 Sip/VoIP 库

c# - 将整数数组传递给 C++ DLL

ruby - 为什么不能将类用作模块?

Python:从父类(super class)构造多重继承子类实例

c# - FormsAuthentication.RedirectToLoginPage() 什么都不做

c# - 仅在 .net 中的正则表达式灾难性回溯

c++ - 是否可以在一个对象中创建一个对象,该对象的构造函数是在 C++ 中从中创建它的对象

c++ - 为什么这个对象没有检测到父类?

c++ - 抽象类和唯一指针

python - 访问 python 父类(super class)属性时遇到问题