如何使用字符串值为Type <t>参数传递Type?

时间:2017-10-11 15:23:46

标签: c# generics

我正在尝试在Student中创建School的对象列表。代替StudentSchool也可以Teacher作为列表。我想在启动类时使用类名作为参数而不是实际的类类型作为参数。

public class Program
{
    static void Main(string[] args)
    {
       //School object with list of student
        var schoolWithStudent = SchoolWithOject("Student");
        //School object with list of teacher
        var schoolWithTeacher = SchoolWithOject("Teacher");
    }

    public static object SchoolWithOject(string objType)
    {
        var objType = Type.GetType("objType");
        var school = new School<objType>();
        return school;
    }   
}

public class School<T>
{
    public int Id;
    public string Name;
    private List<T> _components;

    public School()
    {
        _components = new List<T>();
    }
}

public class Student
{
    public int Id;
    public string Name;
}

public class Teacher
{
    int Id;
    string Name;
}

1 个答案:

答案 0 :(得分:0)

如果我正确理解您的问题并且您不会被迫使用泛型,我会推荐以下解决方案。

由于学校包含学生和教师,您可以为这两种类型实现界面。

interface IPerson
{
    public int Id;
    public string Name;
}

class Student : IPerson
{
    // student specific stuff
}

class Teacher : IPerson
{
    // teacher specific stuff
}

所以你的学校看起来像这样:

public class School
{
    public int Id;
    public string Name;
    private List<Person> _persons;

    public School()
    {
        _persons = new List<Person>();
    }
}