构造函数链接多个调用

时间:2009-03-26 16:43:15

标签: c# .net constructor chaining

根据我的代码,有没有一种方法可以让第一个WebTestingApp构造函数在返回新实例之前调用第二个?我想在构造函数中设置一些只读字段,除了复制/粘贴之外,我无法看到我的能力。

我觉得答案将与构造函数链接有关,但我无法弄清楚如何去做,因为第二个WebTestingApp构造函数隐式调用base()(这对于类的外部用户来说很重要不得不提供IRemoteFile和IWebServiceGateway实例。

    internal WebTestingApp(Result result, BrowserApp browserApp, IRemoteFile remoteFile, IWebServiceGateway webServiceGateway) : base(remoteFile, webServiceGateway)
    {
        // TODO: Need to invoke WebTestingApp(Result result, BrowserApp browserApp)
    }

    public WebTestingApp(Result result, BrowserApp browserApp)
    {
        // Set readonly vars here
    }

这是基类TestingApp的构造函数:

    protected TestingApp() : this(S3File.Instance, WebServiceGateway.Instance) { }

    internal TestingApp(IRemoteFile remoteFile, IWebServiceGateway webServiceGateway)
    {
        this.remoteFile = remoteFile;
        this.webServiceGateway = webServiceGateway;
    }

WebTestingApp派生自TestingApp。 S3File和WebServiceGateway是单身人士。

2 个答案:

答案 0 :(得分:2)

您可以像这样切换逻辑:

internal WebTestingApp(Result result, BrowserApp browserApp, IRemoteFile remoteFile, IWebServiceGateway webServiceGateway) : base(remoteFile, webServiceGateway)
{
    // Set readonly vars here
}

public WebTestingApp(Result result, BrowserApp browserApp) : this(result, browserApp, S3File.Instance, WebServiceGateway.Instance)
{
}

这也不是一个完美的解决方案,因为它复制了两个类中对单身人士的调用。

答案 1 :(得分:0)

抱歉,我想我可能已经找到了答案,通过切换它们并让第二个构造函数调用第一个使用默认的IRemoteFile和IWebServiceGateway实例,我可以将它们链接在一起并包含所有4个构造函数。

    internal WebTestingApp(Result result, BrowserApp browserApp, IRemoteFile remoteFile, IWebServiceGateway webServiceGateway) : base(remoteFile, webServiceGateway)
    {
        // Set readonly fields here
    }

    public WebTestingApp(Result result, BrowserApp browserApp) : this(result, browserApp, S3File.Instance, WebServiceGateway.Instance) {}