构造函数链接与基本构造函数调用相结合
假设我有以下内容:
class Base {
public Base (int n) { }
public Base (Object1 n, Object2 m) { }
}
class Derived : Base {
string S;
public Derived (string s, int n) : base(n) {
S = s;
}
public Derived (string s, Object1 n, Object2 m) : base(n, m) {
S = s; // repeated
}
}
请注意,在 Derived 的两个重载中我如何需要形式参数 n,因此我必须重复 N = n;
行。
现在我知道这可以封装到一个单独的方法中,但您仍然需要从两个重载中调用相同的两个方法。那么,是否有一种更“优雅”的方式来做到这一点,也许可以将 this
与 base
结合使用?
这样我就可以拥有一个带有一个参数 s
的私有构造函数,而其他两个重载可以调用该参数......或者这可能与拥有一个单独的私有方法相同吗?
Say I have the following:
class Base {
public Base (int n) { }
public Base (Object1 n, Object2 m) { }
}
class Derived : Base {
string S;
public Derived (string s, int n) : base(n) {
S = s;
}
public Derived (string s, Object1 n, Object2 m) : base(n, m) {
S = s; // repeated
}
}
Notice how I need formal argument n in both overloads of the Derived and thus I have to repeat the N = n;
line.
Now I know that this can be encapsulated into a separate method but you still need the same two method calls from both overloads. So, is there a more 'elegant' way of doing this, maybe by using this
in conjunction with base
?
This is so that I can have a have a private constructor taking one argument s
and the other two overloads can call that one...or is this maybe just the same as having a separate private method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对此没有理想的解决方案。有一种方法可以避免在
Derived
构造函数中重复代码,但是您必须重复m
参数的默认值:There is no ideal solution for that. There is a way to avoid repeating the code in the
Derived
constructors, but then you have to repeat the default value of them
parameter:只是有一点点进步,但是……
Only a slight improvement, but...