This question already has an answer here:
Say I have a class structure like this:
public class Student
{
}
public class Undergraduate : Student
{
}
public class Postgraduate : Student
{
}
Is it possible to return an instance of all the classes that inherit from Student in a list like this:
List<Student> Student = new List<Student>
I am wandering if this can be done using reflection:
Student.Add(new PostGraduate);
Student.Add(new UnderGraduate);
I believe I have to use reflection for this. I have tried this:
var type = typeof(Student);
var types = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(s => s.GetTypes())
.Where(p => type.IsAssignableFrom(p));
However, this does not return a type of Undergraduate and a type of graduate in a list.
Aucun commentaire:
Enregistrer un commentaire