【问题标题】:Constructor chaining with multiple calls具有多个调用的构造函数链接
【发布时间】:2009-03-26 16:43:14
【问题描述】:

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

【问题讨论】:

    标签: c# .net constructor chaining


    【解决方案1】:

    你可以像这样切换逻辑轮次:

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

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

    【讨论】:

    • 我不确定这行得通吗?它不会尝试使用 IRemoteFile 和 IWebServiceGateway 实例调用 WebTestingApp(Result, BrowserApp) 吗?
    • 我误读了您的问题。道歉。将编辑我的答案。
    • 编辑了我的,然后看到你会想出同样的方法。哦,好吧,很高兴你被分类了......
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-14
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 2012-01-29
      • 1970-01-01
      相关资源
      最近更新 更多