数据我有一个接口泛型类返回特定的一组取决于类型
两个类继承这个接口FetchFromDatabase
和FetchFromCollection
。目的是在注入到另一个类的类之间切换,让我们把它们放在屏幕上等等。根据使用的类型,我想根据类型从特定集合中获取数据。在FetchFromDatabase
中实现此功能并不是问题,因为DbContext
有方法DbContext.Set<>()
,它返回特定的表。
我正在寻找使用集合的方式。在FetchFromCollection
行23:return modules.Set();
,编译器报告错误:
Error 2 Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<MainProgram.Models.Module>' to 'System.Collections.Generic.IEnumerable<TEntity>'. An explicit conversion exists (are you missing a cast?)
我不知道该怎么Module
类转化为泛型类型TEntity
。我尝试使用中级类ModelBase
并继承到具体的定义,但是接下来我将不得不使用另一个注入级别并自行决定要使用哪个具体类。
我在这里找到了一些东西Pass An Instantiated System.Type as a Type Parameter for a Generic Class这是使用反射的方式。我仍然困惑如何实现这一点。有什么建议吗?
FetchFromDatabase
public class FetchFromDatabase<TEntity> : IFetchData<TEntity>
where TEntity : class
{
private readonly MainDBContextBase context;
public FetchFromDatabase(MainDBContextBase context)
{
if (context == null)
throw new ArgumentNullException("DB context");
this.context = context;
}
public IEnumerable<TEntity> GetItems()
{
return context.Set<TEntity>();
}
}
FetchFromCollection
public class FetchFromCollection<TEntity> : IFetchData<TEntity>
where TEntity : class
{
private readonly InitializeComponents components;
private ModelModules modules;
private ModelSpecializations specializations;
private ModelTeachers techers;
private ModelStudents students;
public FetchFromCollection(InitializeComponents components)
{
if (components == null)
throw new ArgumentNullException("Context");
this.components = components;
}
public IEnumerable<TEntity> GetItems()
{
if (typeof(TEntity) == typeof(Module))
{
if (modules == null)
modules = new ModelModules(components);
return modules.Set();
}
return null;
}
}
为什么实现接口泛型的类?你为什么不写:public class FetchFromCollection:IFetchData。 –
但是如果我这样做,'FetchFromCollection'将只返回一个集合。我想根据类型返回不同的集合,类似于什么'DbContext <> Set <>。()'does – Celdor
那么为什么你写“if(typeof(TEntity)== typeof(Module))”?也许你可以详细说明ModelModules? –