I want to iterate through types in an assembly and if a type is a subclass of a specified interface, I want to create an object of the type and add it to a list like so:
var tasks = new List<IScheduledTask>();
foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
{
if (t.IsSubclassOf(typeof(IScheduledTask)))
{
tasks.Add(new t());
}
}
Obviously this above does not work. How can you achieve what I am seeking?
Activator.CreateInstance
is what you're after.
var tasks = new List<IScheduledTask>();
foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())
{
if (t.IsSubclassOf(typeof(IScheduledTask)))
{
tasks.Add((IScheduledTask)Activator.CreateInstance(t));
}
}
Look at using the Activator.CreateInstance method:
ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);
This previous question may help Instantiate an object with a runtime-determined type
It uses Activator.CreateInstance
Activator.CreateInstance(t);
will do the trick.
Be careful though, the class you want to instanciate must have a public constructor with no argument for it to work.
精彩评论