小编GxF*_*int的帖子

如何使用其类型名称实例化泛型类?

在我的项目(.NET 3.5)中,我得到了许多像这样的DAO :(每个实体一个)

public class ProductDAO : AbstractDAO<Product> 
{...}
Run Code Online (Sandbox Code Playgroud)

我需要创建一个函数,它将接收DAO的名称或其实体的名称(无论你认为哪种方式最好)并运行DAO"getAll()"函数.像这个代码只为一个实体做:

ProductDAO dao = new ProductDAO();
dao.getAll();
Run Code Online (Sandbox Code Playgroud)

我是C#的新手,我怎么能用反射做到这一点?

喜欢这样:

String entityName = "Product";
AbstractDAO<?> dao = new AbstractDAO<entityName>()
dao.getAll();
Run Code Online (Sandbox Code Playgroud)

编辑

我忘记了一个细节,这是getAll()返回的方式:

IList<Product> products = productDao.getAll();
Run Code Online (Sandbox Code Playgroud)

所以我还需要在列表中使用反射.怎么样?

Type daoType = typeof(AbstractDAO<>).Assembly.GetType("Entities.ProductDAO");
Object dao = Activator.CreateInstance(daoType);
object list = dao.GetType().GetMethod("getAll").Invoke(dao, null);
Run Code Online (Sandbox Code Playgroud)

c# reflection .net-3.5

4
推荐指数
1
解决办法
2231
查看次数

1
推荐指数
1
解决办法
141
查看次数

标签 统计

.net-3.5 ×1

actionscript-3 ×1

apache-flex ×1

c# ×1

reflection ×1