C# .NET 设计模式问题

标签 c# .net design-patterns

我正在努力实现最佳的代码可重用性。问题是我无法通过存储库从主程序访问位于基本抽象类中的基本方法。

如果您浏览下面的示例,您将看到我所处情况的示例代码。

所以我的问题是如何从主程序访问位于基本抽象类中的方法。

类/接口(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/

相关文章:

c# - 策略模式对这种情况有帮助吗?

c++ - 在组合的情况下访问 'inner' 类

Java正确解析

c# - 满足特定条件的 Array.BinarySearch

.net - 在 Windows 窗体应用程序中使用 C++/CLI 的命名空间混淆

具有内部泛型的 C# 转换对象

c# - 如何测量给定字体/大小的数字的像素宽度 (C#)

c# - 从 C# 调用 c 方法

c# - UWP MediaPlaybackList 在列表项之间弹出声音

c# - 在 C# 中如何为方程分配上标?