遍历给定名称空间中的所有类,并为每个类创建一个对象? [英] Loop through all classes in a given namespace and create an object for each?

查看:36
本文介绍了遍历给定名称空间中的所有类,并为每个类创建一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以遍历命名空间中的每个类并为每个类初始化一个对象?

Is it possible to loop through each class in a namespace and initialize an object for each class?

例如,我想遍历Test.POS命名空间中的所有类,为每个类创建一个对象,然后在每个对象上调用 runImportProcess 方法.

For instance, I want to loop through all classes in the Test.POS namespace, create an object for each class, and call the runImportProcess method on each object.

我知道我可以像这样遍历命名空间:

I know that I can loop through a namespace like so:

Type[] typelist = GetTypesInNamespace(Assembly.GetExecutingAssembly(), 
                                      "Test.POS");

foreach (Type t in typelist)
{
    Console.WriteLine(t.Name);
}

我不确定是否可以使用此 t 变量来完成我想要的事情.对新手有什么见识?

I'm not sure if it's possible to use this t variable to accomplish what I want. Any insight for a novice?

推荐答案

尝试 Assembly.GetTypes().然后按名称空间过滤它们(并确保它们是您想要的).要实例化它们,请使用 Activator.CreateInstance(...).

Try Assembly.GetTypes(). Then filter them by the namespace (and ensure they are what you want). To instantiate them, use Activator.CreateInstance(...).

这篇关于遍历给定名称空间中的所有类,并为每个类创建一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆