具有多个调用的构造函数链
鉴于我下面的代码,有没有办法让第一个 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 是单例。
Given my code below, is there a way that the first WebTestingApp constructor can call the second before returning the new instance? I want to set some readonly fields in the constructor and, short of copy/pasting, I can't see how I can.
I feel that the answer will have something to do with constructor chaining, but I can't figure out how to do it, since the second WebTestingApp constructor implicitly calls base() (which is important as external users of the class shouldn't have to provide IRemoteFile and IWebServiceGateway instances).
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
}
Here's the base class TestingApp's constructors:
protected TestingApp() : this(S3File.Instance, WebServiceGateway.Instance) { }
internal TestingApp(IRemoteFile remoteFile, IWebServiceGateway webServiceGateway)
{
this.remoteFile = remoteFile;
this.webServiceGateway = webServiceGateway;
}
WebTestingApp is derived from TestingApp. S3File and WebServiceGateway are singletons.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以像这样切换逻辑:
这也不是一个完美的解决方案,因为它重复了对两个类中的单例的调用。
You could switch the logic round like this:
This isn't a perfect solution either, as it duplicates the calls to the singletons in both classes.
抱歉,我想我可能已经找到了答案,通过切换它们并让第二个构造函数使用默认的 IRemoteFile 和 IWebServiceGateway 实例调用第一个构造函数,我可以将它们链接在一起并包含所有 4 个构造函数。
Sorry, I think I might've found the answer, by switching them around and having the second constructor call the first with the default IRemoteFile and IWebServiceGateway instances I can chain them together and include all 4 constructors.