0

鉴于下面的代码,第一个 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 是单例。

4

2 回答 2

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)
{
}

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

于 2009-03-26T16:47:11.897 回答
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) {}
于 2009-03-26T16:57:49.000 回答