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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With