开发者

How to create/instantiate an object of 'Type' [duplicate]

This question already has answers here: How to create a new object instance from a Type (11 answers) 开发者_StackOverflow社区 Closed 9 years ago.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜