[英]C#: Can I code public class MyGenericClass<T> where T:MyClass AND implement an Interface?
I see this: 我看到这个:
public class MyGenericClass<T> where T:IComparable { }
and I have this: 我有这个:
public class ProductRepository : IRepository<Product> { }
How would you code something like this? 您将如何编写这样的代码?
public class ProductRepository<T> where T : Product : IRepository<Product> {}
After all that, I thought I could simply make a single Repository class then inject the type to it, including the data context. 毕竟,我认为我可以简单地创建一个Repository类,然后将类型(包括数据上下文)注入其中。 But, we pursue the simplest thing first right?
但是,我们首先追求最简单的东西吧? LOL
大声笑
Update: 更新:
If I did this, how would I choose which Entity to use in the Entity Container (or Context)? 如果这样做,我将如何选择在实体容器(或上下文)中使用哪个实体? (Third line from the bottom starting with return _dc.Versions., which would somehow need switched to return _dc.T. )
(从底部开始的第三行以return _dc.Versions。开头,这将以某种方式需要切换以返回_dc.T。。)
public class Repository<T> : IRepository<T> where T : class
{
# region Constructor
private AdSketchEntities _dc { get; set; } // Data Container (Data Context)
public Repository() : this(new AdSketchEntities()) { }
public Repository(AdSketchEntities myDC)
{ this._dc = myDC;
}
# endregion
public T Add(T entity)
{
_dc.Versions.AddObject(entity);
return _dc.Versions.Where(n => n.custid == entity.custid &&
n.versionid == entity.versionid).SingleOrDefault();
}
You can specify multiple constraints like this: 您可以指定多个约束,如下所示:
public class ProductRepository<T>
where T : Product, IRepository<Product>
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.