我有这个抽象类:
public abstract class Entity<T> where T : struct
{
public T ID { get; set; }
... other properties for modify
}
我想要做的是在IRepository中实现此类。我试过的是这个:
public interface IRepository<T> where T : Entity<T> //Entity<T> doesn't make sense here i should use either T2 or what should i do?
我也试图使它像这样工作:
public interface IRepository<T> where T : Entity<object>
实现此目标的正确方法是什么?
答案 0 :(得分:1)
我不确定您要达到的目标,但是以下是合法的;您的存储库与Entity类具有相同的通用约束:
public interface IRepository<T> where T: struct
{
Entity<T> GetEntityById(int id);
...
}
或者以下方法可行,但是我不清楚您要如何使用T
:
public interface IRepository<T,U> where T : Entity<U> where U: struct
{
Entity<U> GetEntityById(int id);
}
答案 1 :(得分:1)
您可以定义以下抽象:
public abstract class Entity<TKey>
where TKey : struct
{
public TKey Id { get; set; }
}
public interface IRepository<TEntity, TKey>
where TEntity : Entity<TKey>
where TKey : struct
{
IEnumerable<TEntity> GetAll();
TEntity GetById(TKey id);
}
然后作为用法,例如:
public class Repository<TEntity, TKey> : IRepository<TEntity, TKey>
where TEntity : Entity<TKey>
where TKey : struct
{
DbContext db;
public Repository(DbContext db)
{
this.db = db;
}
public IEnumerable<TEntity> GetAll()
{
return db.Set<TEntity>();
}
public TEntity GetById(TKey id)
{
return db.Set<TEntity>().FirstOrDefault(x => x.Id.Equals(id));
}
}