【发布时间】:2009-11-05 17:52:29
【问题描述】:
我有一个数据访问库,它有几个类都实现了相同的接口,并且有一个泛型类型参数:
public interface IGetByCommonStringRepository<TEntity>
{
TEntity GetByCommonStringColumn(string commonString);
}
public class Repository1<Entity1> : IGetByCommonStringRepository<Entity1>
{
public Entity1 GetByCommonStringColumn(string commonString)
{
//do stuff to get the entity
}
}
public class Repository2<Entity2> : IGetByCommonStringRepository<Entity2>
//...and so on
与其强迫这个库的使用者为每个<TEntity> 分别实例化四个存储库类之一,我希望有某种方法可以在同一个“帮助程序/实用程序”类中创建一个静态方法程序集,它将能够辨别要实例化哪个实现、创建实例并执行GetByCommonStringColumn 方法。有点像...
public static TEntity GetEntityByCommonStringColumn(string commonString) where TEntity : class
{
IGetByCommonStringRepository<TEntity> repository =
DoMagicalReflectionToFindClassImplementingIGetByCommonString(typeof(TEntity));
//I know that there would have to an Activator.CreateInstance()
//or something here as well.
return repository.GetByCommonStringColumn(commonString) as TEntity;
}
这样的事情可能吗?
【问题讨论】:
-
示例代码中的类没有实现
IGetByCommonStringRepository<>。
标签: c# generics reflection interface