代码之家  ›  专栏  ›  技术社区  ›  Matt Brindley

具有多个调用的构造函数链接

  •  0
  • Matt Brindley  · 技术社区  · 16 年前

    给出我下面的代码,有没有一种方法可以让第一个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 回复  |  直到 16 年前
        1
  •  2
  •   David M    16 年前

    您可以这样切换逻辑:

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

        2
  •  0
  •   Matt Brindley    16 年前

    抱歉,我想我可能已经找到了答案,通过切换它们,让第二个构造函数使用默认的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) {}