如何继承的构造函数? [英] How to inherit constructors?

查看:121
本文介绍了如何继承的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象的基类有许多构造函数和一个虚方法

Imagine a base class with many constructors and a virtual method

public class Foo
{
   ...
   public Foo() {...}
   public Foo(int i) {...}
   ...
   public virtual void SomethingElse() {...}
   ...
}

现在我想创建一个子类,它覆盖的虚方法:

and now i want to create a descendant class that overrides the virtual method:

public class Bar : Foo 
{
   public override void SomethingElse() {...}
}

和另一个后裔,做一些更多的东西:

And another descendant that does some more stuff:

public class Bah : Bar
{
   public void DoMoreStuff() {...}
}

我真的必须从富所有构造复制到酒吧和Bah?然后,如果我在富更改构造函数签名的,我要在酒吧和Bah更新它?

Do i really have to copy all constructors from Foo into Bar and Bah? And then if i change a constructor signature in Foo, do i have to update it in Bar and Bah?

有没有办法继承的构造函数?有没有办法来鼓励code重用?

Is there no way to inherit constructors? Is there no way to encourage code reuse?

推荐答案

是的,你将必须实现,对于每个派生意义的构造函数,然后使用关键字的构造直接到相应的基类或这个关键字直接构造到另一个构造在同一类。

Yes, you will have to implement the constructors that make sense for each derivation and then use the base keyword to direct that constructor to the appropriate base class or the this keyword to direct a constructor to another constructor in the same class.

如果编译器在关于继承构造的假设,我们将不能够正确地确定我们的对象是如何被实例化。在大多数情况下,你应该考虑你为什么有这么多的构造函数,并考虑把他们变成只有一个或两个基类。然后,派生类可以屏蔽掉其中的一些使用常量像只有通过它们的构造函数暴露必要的。

If the compiler made assumptions about inheriting constructors, we wouldn't be able to properly determine how our objects were instantiated. In the most part, you should consider why you have so many constructors and consider reducing them to only one or two in the base class. The derived classes can then mask out some of them using constant values like null and only expose the necessary ones through their constructors.

在C#4你​​可以指定默认的参数值,并使用命名参数,使一个构造函数支持多种参数配置,而不​​是每个配置一个构造函数。

In C#4 you could specify default parameter values and use named parameters to make a single constructor support multiple argument configurations rather than having one constructor per configuration.

这篇关于如何继承的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆