gpt4 book ai didi

c# - 在 C# 4 中,如何在具有重载构造函数的父类的子类中拥有带可选参数的构造函数?

转载 作者:太空狗 更新时间:2023-10-29 23:26:18 24 4
gpt4 key购买 nike

我有一个父类有一个重载的构造函数,我有一个子类有一个带可选参数的构造函数。有没有办法让子类的构造函数仍然暴露父类的重载性,同时保留它自己的可选参数?

下面是这两个类的一些示例代码及其所需的构造函数:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com