use*_*086 4 .net c# design-patterns
我正在尝试实现最佳代码重用性.问题是我无法通过存储库访问位于主程序的Base Abstract类中的基本方法.
如果您通过下面的示例,您将看到我的情况的示例代码.
所以我的问题是如何从主程序访问基本抽象类中的方法.
类/接口
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>();
//
}
}
Run Code Online (Sandbox Code Playgroud)
//主应用
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);
}
}
Run Code Online (Sandbox Code Playgroud)
Rap*_*aus 10
接口中未定义GetById
我会做一个
public interface IBaseRepository<T> where T : BaseEntitiy {
T GetById<T>(int id);
}
Run Code Online (Sandbox Code Playgroud)
然后BaseClass实现IBaseRepository<T>
并IFooRepository继承自IBaseRepository<Foo>
编辑:
一个完整的例子,类似于@Olivier JD,带有想法(可能是错误的),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
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
380 次 |
| 最近记录: |