c# - 在 C# 中使用泛型 - 从泛型类调用泛型类

标签 c# .net generics .net-4.0

我有一个类似于下面的类:

public abstract class Manager<T, TInterface> : IManager<T> where TInterface : IRepository<T>
{
    protected abstract TInterface Repository { get; }

    public virtual List<T> GetAll()
    {
        return Repository.GetAll();
    }
}

这工作得很好,但是,有没有办法避免在抽象类声明和扩展我的通用抽象类的结果类中使用 TInterface:

public class TestManager : Manager<TestObject, ITestRepository>, ITestManager

我被迫使用 ITestRepository 并将 Repository 属性抽象化,因为它可以包含我需要了解并能够调用的自定义方法。

随着我继续构建层,我将不得不在堆栈的整个过程中继续执行此过程。例如,如果我有一个通用的抽象 Controller 或服务层:

public class TestService : Service<TestObject, ITestManager>, ITestService

有没有更好的方法来做到这一点,或者这是允许泛型类调用另一个泛型类的最佳实践吗?

最佳答案

看来你只想做Manager<T>可测试,并使用模拟作为存储库,您可以查询特殊成员。

如果是这种情况,也许您可​​以将设计更改为:

public class Manager<T> : IManager<T> {
  protected IRepository<T> Repository { get; set; }
  // ...
  public virtual List<T> GetAll() {
    return Repository.GetAll();
  }
}

现在,测试的所有细节都在测试子类中:

public class TestingManager<T> : Manager<T> {
  public new ITestRepository<T> Repository {
    get {
      return (ITestRepository<T>)base.Repository;
    }
    set {
      base.Repository = value;
    }
  }
}

编写单元测试时,您创建了 TestingManager<T>实例(通过 TestingManager<T> 声明的变量和字段引用),并为它们提供测试存储库。每当你查询他们的Repository ,您将始终获得强类型测试存储库。

更新:

还有另一种方法可以解决这个问题,无需子类。您将存储库对象声明为传递给 Manager<T> 的测试存储库s 并且您直接查询它们,而无需通过 Manager<T> .

[Test]
public void GetAll_Should_Call_GetAll_On_Repository_Test() {
  var testRepository = new TestRepository();
  var orderManager = new Manager<Order>(testRepository);
  // test an orderManager method
  orderManager.GetAll();
  // use testRepository to verify (sense) that the orderManager method worked
  Assert.IsTrue(testRepository.GetAllCalled);
}

关于c# - 在 C# 中使用泛型 - 从泛型类调用泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3353517/

相关文章:

c# - 创建 XML 文档的最佳 .net 方法

c# - List.add 使用 Linq

c# - WebException 响应未返回完整响应

swift - Swift 4 中的通用解码器

c# - 无法从根提供程序解析范围服务 'Microsoft.AspNetCore.Identity.UserManager` 1[IdentityServerSample.Models.ApplicationUser]'

c# - 如何阻止 Spyne 将参数包装在复杂类型中?

c# - 在异步上下文中添加到字典时出现 NullReferenceException

.net - 是否可以在不使用Windows Media Player的情况下获取WMA文件的长度?

c++ - 通用继承和复制构造函数

java - 在 hashmap 中一般实现方法中传递参数