[英]Base class with a generic type which implements an interface with a generic type
我正在實現一個存儲庫模式,並且我希望FooRepository
對於實現IEntity
所有模型IEntity
但是IDE(Rider)說Type parameter 'IEntity' hides interface 'IEntity'
,后來出現了一個錯誤消息Cannot resolve symbol 'ID'
在GetById
方法中Cannot resolve symbol 'ID'
。
為泛型類型(在本例中為IEntity
)創建基類的正確方法是什么,該類也實現采用相同泛型類的接口?
最終目標是將FooRepository
用於其他模型(而不是Bar
)作為GetById
之類的方法,因為它們之間的功能大致相同。
public abstract class FooRepository<IEntity> : IRepository<IEntity>
{
private List<IEntity> _data;
public List<IEntity> GetAll()
{
return this._data;
}
public IEntity GetById(int id)
{
return this.GetAll().Single(c => c.ID == id);
}
}
public class BarRepository : FooRepository<Bar>
{
}
public interface IEntity
{
int ID { get; set; }
}
public interface IRepository<IEntity>
{
List<IEntity> GetAll();
IEntity GetById(int id);
}
public class Bar : IEntity
{
public int ID { get; set; }
public string Name { get; set; }
}
我通過使用泛型來修復您的抽象類。
public abstract class FooRepository<T> : IRepository<T> where T: IEntity
{
private List<T> _data;
public List<T> GetAll()
{
return this._data;
}
T IRepository<T>.GetById(int id)
{
return this.GetAll().Single(c => c.ID == id);
}
}
public class BarRepository : FooRepository<Bar>
{
}
public interface IEntity
{
int ID { get; set; }
}
public interface IRepository<T>
{
List<T> GetAll();
T GetById(int id);
}
public class Bar : IEntity
{
public int ID { get; set; }
public string Name { get; set; }
}
我確實認為更好(更簡單)的解決方案是:
public abstract class FooRepository<T> where T: IEntity
{
private List<T> _data;
public List<T> GetAll()
{
return this._data;
}
T GetById(int id)
{
return this.GetAll().Single(c => c.ID == id);
}
}
public class BarRepository : FooRepository<Bar>
{
}
public interface IEntity
{
int ID { get; set; }
}
public class Bar : IEntity
{
public int ID { get; set; }
public string Name { get; set; }
}
您不需要IRepository接口,因為您的抽象類涵蓋了這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.