作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个父类有一个重载的构造函数,我有一个子类有一个带可选参数的构造函数。有没有办法让子类的构造函数仍然暴露父类的重载性,同时保留它自己的可选参数?
下面是这两个类的一些示例代码及其所需的构造函数:
class Foo {
Foo(String arg0)
{
// do some stuff with arg0
}
Foo(String arg0, List<x> arg1)
: this(arg0)
{
// do some other stuff with arg1 that is special because we have an arg1
}
}
class Bar : Foo {
Bar(String arg0, List<y> arg2 = null, String arg3 = "")
: base(arg0)
{
// some third thing with arg2 and arg3
}
}
这是另一个子类构造函数的方法签名,我还想公开父构造函数的重载,但问题是如何去做:
Bar(String arg0, List<x> arg1, List<y> arg2 = null, String arg3 = "")
我认为,我已经找到了解决方案,但我不确定它是否尽可能干净。我已将其作为答案发布,以防万一它是唯一的选择。
最佳答案
如果您可以将 Foo
更改为只有一个带有可选参数的构造函数,您可以执行以下操作:
public class Foo
{
public Foo(String arg0, List<x> arg1 = null)
{
// do some stuff with arg0
if (arg1 != null)
{
// do some other stuff with arg1
}
}
}
public class Bar : Foo
{
public Bar(String arg0, List<x> arg1 = null, List<y> arg2 = null, String arg3 = "")
: base(arg0, arg1)
{
// some third thing with arg2 and arg3
}
}
关于c# - 在 C# 4 中,如何在具有重载构造函数的父类的子类中拥有带可选参数的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5915825/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!