我有两层对象层次结构,如下所示:
public class BaseStat
{
}
public class IndividualDefensiveStat: BaseStat
{
} //and many other stats that inherit from BaseStat
然后我有一个像这样的通用存储库:
public class StatRepository<TDerived> where TDerived: BaseStat
{
//ctr here
public TDerived FindById(int? id)
{
if(!id.HasValue)
throw new Exception("id has to have a value");
var result = _context.Set<TDerived>().Find(id);
return result;
}
public void Insert(TDerived item)
{
_context.Set<TDerived>().Add(item);
_context.SaveChanges();
}
}
最后,我有一个接受数据上下文的服务类,并根据传入的派生类型执行CRUD操作:
public class StatDataService
{
private IStatContext _context;
public StatDataService(IStatContext context)
{
_context = context;
}
public void InsertData<TEntity>(TEntity item) where TEntity : BaseStat
{
var repo = getRepository<TEntity>();
repo.Insert(item);
}
public TEntity GetById<TEntity>(int? id) where TEntity : BaseStat
{
return getRepository<TEntity>().FindById(id);
}
private StatRepository<TEntity> getRepository<TEntity>() where TEntity: BaseStat
{
return new StatRepository<TEntity>(_context);
}
}
我想要一个BaseStat列表,其中包含从中派生的项目。但是,如果我执行foreach循环并将每个项目传递到Service的Insert方法,则在这种情况下TEntity / TDerived是BaseStat。
我怎样才能让TEntity / TDerived成为我想要定位的DerivedType?