【问题标题】:functions with a subclass parameter带有子类参数的函数
【发布时间】:2012-07-23 08:45:36
【问题描述】:

所以我得到了一个类 Person,它包含年龄、性别、姓名(和主键 ID)。 然后我得到了两个人的子类:

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 种方法。 (实际上还有更多,但可以解决我将使用这些问题的问题)

这就是我的想法:

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 然后 true 或 flase 但不/p>

【问题讨论】:

  • 不是真的我在做一个项目,我们正在制作一个从 EF 模型获取数据的 WCF 服务,但是我们在对象上使用了继承,因此它们永远不会获得相同的 ID。我正在做的项目是 smartp1ck(dot)com。我只是快速写了这篇文章来解释我的问题我必须承认它看起来像家庭作业^^。
  • 只是想知道 - 你的类只是名称不同,或者它们有不同的行为?
  • 它们确实有不同的功能,并且它们与其他表(在数据库中)链接

标签: c# class inheritance


【解决方案1】:

建议的班级设置:

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

【讨论】:

  • 注意:如果子类有不同的参数,使用工厂甚至可以处理,通过检查if(typeof(T) == typeof(Teacher)
  • 好吧,谢谢这解决了它,还需要 typeof 的注释,因为我确实得到了具有不同参数的子类,谢谢。稍后我将在我的 WCF 服务中实现这一点
【解决方案2】:

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

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; 
}

【讨论】:

    猜你喜欢
    • 2021-07-05
    • 2016-12-30
    • 1970-01-01
    • 2021-08-09
    • 2011-05-07
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 2016-08-08
    相关资源
    最近更新 更多