代码改变世界

How to inherit constructors?

2011-08-02 16:34  一一九九  阅读(219)  评论(0编辑  收藏  举报

from: http://stackoverflow.com/questions/223058/how-to-inherit-constructors

问题大体如下:

假设有一个基类:

public class Foo
{
   ...
   public Foo() {...}
   public Foo(int i) {...}
   ...
   public virtual void SomethingElse() {...}
   ...
}
然后创建了一个继承类去继承自Foo
public class Bar : Foo 
{
   public override void SomethingElse() {...}
}
问题: 此时能否 Bar bar = new  Bar(5)?
注: 如果是在Delphi中的,那么肯定是可以调用的。
答案是:

 

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.

Update

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.

关键的一句话是:If the compiler made assumptions about inheriting constructors, we wouldn't be able to properly determine how our objects were instantiated.

假设在Class Bar 中存在某个Property 类型是Object,而这个需要在Constructor中去初始化,如果调用类Foo的构造方法 Foo(int i), 此时是不能够对这个Property进行初始化的。这算是编译器做的防止错误的一种方式吧。