我应该如何在类层次结构中链接构造函数?
我们有以下类层次结构:
public class Base
{
public Base()
{
// do generic initialization
}
public Base(SomeClass param1) : this()
{
// init properties that require param1
}
public Base(SomeClass param1, OtherClass param2) : this(param1)
{
// init properties that require param2
}
// ...
}
public class Derived : Base
{
public Derived()
{
// do custom initialization
}
public Derived(SomeClass param1) : this() // ???
{
// do custom initialization using param1
}
public Derived(SomeClass param1, OtherClass param2) : this(param1) // ???
{
// do custom initialization using param2
}
// ...
}
我们需要 Derived
运行其自己的初始化例程(沿着链向上)以及来自基类的相应初始化例程。我们如何链接构造函数而不重复代码/运行某些构造函数两次?
We have the following class hierarchy:
public class Base
{
public Base()
{
// do generic initialization
}
public Base(SomeClass param1) : this()
{
// init properties that require param1
}
public Base(SomeClass param1, OtherClass param2) : this(param1)
{
// init properties that require param2
}
// ...
}
public class Derived : Base
{
public Derived()
{
// do custom initialization
}
public Derived(SomeClass param1) : this() // ???
{
// do custom initialization using param1
}
public Derived(SomeClass param1, OtherClass param2) : this(param1) // ???
{
// do custom initialization using param2
}
// ...
}
We would require Derived
to run both its own initialization routines, up the chain, and the corresponding ones from the base class. How do we chain the constructors without duplicating code/running some of the constructors twice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在派生类中,将参数最少的构造函数链接到参数最多的构造函数,然后将参数最多的派生构造函数链接到基类。像这样的事情:
根据上下文,最好使用 default(T) 而不是 null 来指示缺失/默认值。
In the derived class chain the constructors with the least parameters to the constructor with the most parameters, and then the derived constructor with the most parameters is chained to base. Something like this:
Depending on the context, it may be better to use default(T) instead of null to indicate a missing/default value.
您通常将构造函数链接到最少的构造函数到最多的构造函数,如下所示:
请参阅 上的这篇文章C# 中的构造函数了解更多信息。
编辑:
按照下面的@Scott:
参数最多的一个将是
public Derived(SomeClass param1, OtherClass param2) : base(param1, param2)
并且您将初始化代码放在 2 中派生
和基
中的参数构造函数为了演示调用所有构造函数,我起草了一个程序:
输出:
You generally chain the constructor with least, to the one with most, like this:
See this article on Constructors in C# for more information.
Edit:
As per @Scott below:
The one with the most parameters would then would be
public Derived(SomeClass param1, OtherClass param2) : base(param1, param2)
and you put your initialization code in the 2 parameter constructor in thederived
and thebase
To demonstrate that all constructors are called, I drafted a program:
Output: