我有类Repository,并且基于T我想在我的构造函数中为类型T..创建objectset ...这是我到目前为止所拥有的..
public static class Repository<T> : IDisposable
where T : class
{
private DeltaDBEntities context;
private ObjectSet<T> objectset;
public Repository()
{
this.context = new DeltaDBEntities();
switch
{
case T = typeof(ViewModels.Company):
this.objectset = context.Companies;
break;
}
this.objectset = context.Set
}
答案 0 :(得分:1)
如果您的DeltaDBEntities
继承自ObjectContext
,则可以使用其通用方法CreateObjectSet<T>()
。
public class Repository<T> where T : class
{
private DeltaDBEntities context;
private ObjectSet<T> objectset;
public Repository()
{
this.context = new DeltaDBEntities();
this.objectset = context.CreateObjectSet<T>();
}
}
答案 1 :(得分:0)
不确定您要实现的目标以及为什么使用泛型来编译在编译时未知的内容,但您可以尝试以下方法:
public class Repository<T> : IDisposable where T : class
{
private DeltaDBEntities context;
private ObjectSet<T> objectset;
public Repository()
{
this.context = new DeltaDBEntities();
if (typeof(T) == typeof(ViewModels.Company))
{
this.objectset = context.Companies;
}
else if (typeof(T) == typeof(ViewModels.SomeOtherClass))
{
this.objectset = context.SomethingElse;
}
else
{
this.objectset = context.Set;
}
}
public void Dispose()
{
// TODO: implement IDisposable
}
}
另请注意,静态类无法实现接口,因此Repository<T>
不应该是静态的。