2015-10-03 58 views
0

数据我有一个接口泛型类返回特定的一组取决于类型

​​

两个类继承这个接口FetchFromDatabaseFetchFromCollection。目的是在注入到另一个类的类之间切换,让我们把它们放在屏幕上等等。根据使用的类型,我想根据类型从特定集合中获取数据。在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; 
    } 
} 
+1

为什么实现接口泛型的类?你为什么不写:public class FetchFromCollection:IFetchData 。 –

+0

但是如果我这样做,'FetchFromCollection'将只返回一个集合。我想根据类型返回不同的集合,类似于什么'DbContext <> Set <>。()'does – Celdor

+0

那么为什么你写“if(typeof(TEntity)== typeof(Module))”?也许你可以详细说明ModelModules? –

回答

1

你尝试明确的转换?

return (IEnumerable<TEntity>)modules.Set(); 
+0

由于某种原因,我以前尝试过的时候给了我错误。这就是我提出这个问题的原因。当我重新构建解决方案时,错误消失。谢谢。问题是有没有更好的方法来做到这一点?我不认为我创造的是最漂亮的方式: – Celdor