- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 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;
}
}
然后您的客户端代码将在其构造函数中同时使用 IValidator
和 IConfiguration
并测试验证器是否验证配置。
public Client(IConfiguration configuration, IValidator validator)
{
if(!validator.Validate(configuration))
{
throw new ConfigurationErrorsException();
}
}
这种技术的好处是您可以稍后更改验证器,或者有一个新的实现将多个验证器链接在一起以支持一起“或”ing 和“anding”验证器。
关于c# - 构造函数重构中的虚方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22842223/
我有一个特别的问题想要解决,我不确定是否可行,因为我找不到任何信息或正在完成的示例。基本上,我有: class ParentObject {}; class DerivedObject : publi
在我们的项目中,我们配置了虚 URL,以便用户可以在地址栏中输入虚 URL,这会将他们重定向到原始 URL。 例如: 如果用户输入'http://www.abc.com/partner ',它会将它们
我是一名优秀的程序员,十分优秀!