gpt4 book ai didi

c# - 构造函数重构中的虚方法调用

转载 作者:行者123 更新时间:2023-11-30 17:00:01 24 4
gpt4 key购买 nike

我有一个 Client 类,它在构造函数中接受一个带有 IConfiguration 接口(interface)的对象。

在创建 Client 对象时应验证配置。

public interface IConfiguration
{
int ReconnectDelay { get; }
}

public class Client
{
public Client(IConfiguration configuration)
{
if (configuration.ReconnectDelay < 60000)
{
throw new ConfigurationErrorsException();
}
}
}

出于测试目的,我需要一个 ReconnectDelay 属性设置为低于有效值的客户端。

这是我目前的解决方案:

public class Client
{
public Client(IConfiguration configuration)
{
ValidateConfiguration(configuration);
}

protected virtual void ValidateConfiguration(IConfiguration configuration)
{
if (configuration.ReconnectDelay < 60000)
{
throw new ConfigurationErrorsException();
}
}
}

public class TestClient : Client
{
public TestClient(IConfiguration configuration)
: base(configuration)
{
}

protected override void ValidateConfiguration(IConfiguration configuration)
{
}
}

它可以工作,但会导致在构造函数中调用虚方法,这很糟糕(我知道现在它不会造成任何伤害,但我还是想解决这个问题)。

那么,有什么优雅的解决方案吗?

最佳答案

您可以创建一个具有 2 个实现的验证器接口(interface),然后委托(delegate)给验证器。从技术上讲,这仍然是一个虚拟调用,但它是针对另一个对象的,因此您不必担心 Client 的子类会覆盖调用或访问部分构建的 Client。

public interface IValidator
{
bool Validate (IConfiguration configuration);
}

然后您的正常用例使用 ReconnectionValidator。

public class ReconnectionValidator : IValidator
{

bool Validate (IConfiguration configuration)
{
return configuration.ReconnectDelay >= 60000;
}
}

你的测试Validator总是可以返回true

public class NullValidator : IValidator
{

bool Validate (IConfiguration configuration)
{
return true;
}
}

然后您的客户端代码将在其构造函数中同时使用 IValidatorIConfiguration 并测试验证器是否验证配置。

public Client(IConfiguration configuration, IValidator validator)
{
if(!validator.Validate(configuration))
{
throw new ConfigurationErrorsException();
}
}

这种技术的好处是您可以稍后更改验证器,或者有一个新的实现将多个验证器链接在一起以支持一起“或”ing 和“anding”验证器。

关于c# - 构造函数重构中的虚方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22842223/

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