我有一个Client
类,它在构造函数中接受具有IConfiguration
接口的对象。构造函数重构中的虚拟方法调用
当创建对象时,应该验证配置。
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)
{
}
}
它的工作原理,但会导致调用在构造虚拟方法,这是不好的(我知道现在它不会有什么坏处,但我无论如何要解决这个问题)。
那么,有没有优雅的解决方案呢?
你可以让'TestClient'类成为'sealed'吗? – Dmitry
@Dmitry这将如何帮助?诚实的问题。 –
@Dmitry,我可以使'TestClient'成为密封的,但这里的问题与'Client'类有关。 – bniwredyc