调用第二级基类构造函数 [英] Calling a second level base class constructor

查看:51
本文介绍了调用第二级基类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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.)

这篇关于调用第二级基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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