问题描述
在C#中,我有一个类foo
,它从类bar
继承,该类又从类foobar
继承.
In C#, I have a class, foo
, that inherits from class bar
, which in turn inherits from class foobar
.
在foo
构造函数中,我想直接调用foobar
构造函数,而不是从对bar
构造函数的调用中调用.我尝试过这样的事情:
In the foo
constructor, I want to call the foobar
constructor directly, not from a call to the bar
constructor. I tried something like this:
public foo(int i): base : base(i)
显然这是行不通的.在不通过bar
构造函数的情况下,如何使它工作?
Obviously this does not work. How would you make it work, without passing through the bar
constructor?
推荐答案
您不能,因为您不能跳过bar的初始化.您必须在bar中创建一个构造函数来传递参数.原因是律师有责任决定如何构造其基类. (基类的构造是bar的 implementation 的一部分,而面向对象的原理之一就是封装-将实现隐藏在外部.)
You can't, as you cannot skip the initialization of bar. You have to create a constructor in bar that passes your argument through. The reason is that it's bar's responsibility to decide how it wants its base class to be constructed. (The construction of the base class is part of bar's implementation, and one of the principles of object-orientation is encapsulation -- hiding implementation to the outside.)
这篇关于调用第二级基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!