简体   繁体   中英

How to instantiate a generic class by using its type name?

In my project (.NET 3.5) I got many DAOs like this: (One for every entity)

public class ProductDAO : AbstractDAO<Product> 
{...}

I need to create a function that will receive the name of the DAO or the name of its entity (whatever you think it's best) and run the DAOs "getAll()" function. Like this code does for just one entity:

ProductDAO dao = new ProductDAO();
dao.getAll();

I'm new to C#, how can I do that with reflection?

Someting like this:

String entityName = "Product";
AbstractDAO<?> dao = new AbstractDAO<entityName>()
dao.getAll();

Edit

One detail that I forgot, this is how getAll() returns:

IList<Product> products = productDao.getAll();

So I would also need to use reflection on the list. How?

Solution

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

If you are using generics and don't want to implement a specific DAO for each entity type, you can use this:

Type entityType = typeof(Product); // you can look up the type name by string if you like as well, using `Type.GetType()`
Type abstractDAOType = typeof(AbstractDAO<>).MakeGenericType(entityType);
dynamic dao = Activator.CreateInstance(abstractDAOType); 
dao.getAll();

Otherwise, just do a Type.GetType() with the computed name of the DAO (assuming that you follow a certain convention for the names).

Try:

Type d1 = typeof(AbstractDAO<>);
Type[] typeArgs = {Type.GetType("ProductDAO")};
Type constructed = d1.MakeGenericType(typeArgs);
object o = Activator.CreateInstance(constructed);

o.GetType().GetMethod("getAll").Invoke();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM