我可以继承构造函数吗? [英] Can I inherit constructors?
问题描述
我知道不可能在C#中继承构造函数,但是可能有一种方法可以做我想做的事情。
I know it's not possible to inherit constructors in C#, but there's probably a way to do what I want to do.
我有一个继承的基类由许多其他类组成,它具有 Init
方法,该方法使用1参数进行一些初始化。所有其他继承类也都需要初始化,但是我需要为它们创建单独的构造函数,例如:
I have a base class that is inherited by many other classes, and it has an Init
method that does some initializing taking 1 parameter. All other inheriting classes also need this initializing, but I'd need to create separate constructors for all of them that would like like this:
public Constructor(Parameter p) {
base.Init(p);
}
这完全违反了DRY原则!
That totally violates the DRY principles! How can I have all necessary stuff initialized without creating dozens of constructors?
推荐答案
您无需创建许多构造函数就可以初始化所有必需的东西吗?全部具有相同的代码;您只创建一个,但是派生类调用了基本构造函数:
You don't need to create loads of constructors, all with the same code; you create only one, but have the derived classes call the base constructor:
public class Base
{
public Base(Parameter p)
{
Init(p)
}
void Init(Parameter p)
{
// common initialisation code
}
}
public class Derived : Base
{
public Derived(Parameter p) : base(p)
{
}
}
这篇关于我可以继承构造函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!