我正在努力实现最佳的代码可重用性。问题是我无法通过存储库从主程序访问位于基本抽象类中的基本方法。
如果您浏览下面的示例,您将看到我所处情况的示例代码。
所以我的问题是如何从主程序访问位于基本抽象类中的方法。
类/接口(interface)
public abstract class BaseEntity
{
public override abstract String ToString();
}
public abstract class BaseClass<T> where T : BaseEntity
{
public T GetById(int id)
{
//Dummy Code
return new T();
//
}
}
public interface IFooRepository
{
IList<Foo> GetOrderedObjects();
}
public interface FooRepository : BaseClass<Foo>, IFooRepository
{
public IList<Foo> GetOrderedObjects()
{
//GetById method is accessible from the repository - Fine
var obj = this.GetById(5);
//Dummy Code
return new List<Foo>();
//
}
}
//主应用
public class void Main()
{
private IFooRepository _fooRepository;
public void ProgramStartsHere()
{
//This is ok.
var list = _fooRepository.GetOrderedObjects();
//Problem is here - GetById method is not accessible from the main program through the FooRepository
var obj = _fooRepository.GetById(10);
}
}
最佳答案
接口(interface)中没有定义GetById
我会做一个
public interface IBaseRepository<T> where T : BaseEntitiy {
T GetById<T>(int id);
}
然后 BaseClass
工具 IBaseRepository<T>
和IFooRepository
继承自 IBaseRepository<Foo>
编辑:
一个完整的例子,类似于@Olivier J-D 的例子,有一个想法(可能是错误的),即 GetOrderedObject 可能对所有实体都是相同的。
public abstract class BaseEntity
{
public override abstract String ToString();
}
//all generic methods
public interface IRepositoryBase<T>
where T : BaseEntity, new()
{
T GetById(int id);
IList<T> GetOrderedObjects();
}
//all methods specific to foo, which can't be in a generic class
public interface IFooRepository :IRepositoryBase<Foo>
{
void Update(Foo model);
}
//implementation of generic methods
public abstract class BaseClass<T> : IRepositoryBase<T>
where T : BaseEntity, new() // ===> Add new() constraint here
{
public T GetById(int id)
{
return new T();
}
public IList<T> GetOrderedObjects() {
var obj = this.GetById(5);
//Dummy Code
return new List<Foo>();
//
}
}
//implementation of Foo specific methods
public class FooRepository : BaseClass<Foo>, IFooRepository
{
public void Update(Foo model) {
//bla bla
}
}
关于C# .NET 设计模式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10499289/