我有一个业务逻辑组件以下实现一个通用的接口:实例化一个类使用反射
public class BusinessEntity
{
...
}
public class Customer : BusinessEntity
{
...
}
public interface IEntityManager <T> where T : BusinessEntity
{
T SaveData(T oData);
}
public CustomerEntityManager : IEntityManager <Customer>
{
Customer SaveData(Customer o)
{
...
}
}
我不得不来加载上面的组件(由于几个明显的原因),在我目前的项目通过反思和实例化CustomersEntityManager
。想象一下,我写的方法如下:
public class EntityFactory
{
public static IEntityManager<BusinessEntity> GetManagerInstance(string EntityName)
{
var asm = GetAssembly(); // imagine that I loaded the assembly somehow
EntityName = "Customer"; // just imagine
object o;
// DO NOT KNOW WHAT TO WRITE HERE.
return o as IEntityManager<BusinessEntity>; // this needs to be an instance of CustomerEntityManager.
}
}
我可以选择修改业务程序集。但实例创建需要在我当前的项目中,我必须使用反射来加载业务程序集。所有的数据类型只有在运行时才会知道。
我可能会错过一些根本性的东西,或者可能做错了编码。请帮我解决这个问题。
UPDATE:
遵循 “德里斯” 的建议,像以下:
string fullTypeName = "Your.Namespace." + EntityName + "EntityManager";
object o = Activator.CreateInstance(asm.FullName, fullTypeName);
看起来它创建的实例。然而,它结束了一个错误:
Cannot cast 'o' (which has an actual type of 'CustomerEntityManager') to 'IEntityManager'
时得到执行以下语句:
return o as IEntityManager<BusinessEntity>
感谢
+1 for IoC Framework – smartcaveman
driis,我得到错误当语句“return o as IEntityManager”时,无法将'o'(具有'CustomerEntityManager'的实际类型)转换为'IEntityManager '正在执行。 –
user203687
你不想要IEntityManager?因为这是CustomerEntityManager实现的。 –
driis