GxF*_*int 4 c# reflection .net-3.5
在我的项目(.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)
如果您使用泛型并且不想为每个实体类型实现特定的DAO,则可以使用以下命令:
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();
Run Code Online (Sandbox Code Playgroud)
否则,只需Type.GetType()使用DAO的计算名称(假设您遵循某些约定的名称).