gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:28:06 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com