Calling a second level base class constructor

╄→гoц情女王★ 提交于 2019-12-11 03:27:06

问题


In C#, I have a class, foo, that inherits from class bar, which in turn inherits from class foobar.

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)

Obviously this does not work. How would you make it work, without passing through the bar constructor?


回答1:


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




回答2:


Take whatever shared logic you want to execute out of the foobar constructor.

Create a method in foobar called initialize, the signature would be void initialize(int i)

Call this method from the constructor in foo.

Of course, this won't skip the constructor in bar.




回答3:


I think you're trying to get some specific behavior from a language feature that's not designed to work that way. Kind of similar to, for example, using exceptions to control normal application flow.

Perhaps you could give us more details and then get an advice that's more appropriate to what you're trying to do.




回答4:


+1 Agree it bar's responsibility to decide how it wants to be constructed. I came out the code like below so you can use default constructor (bar) and allow override the constructor

public class bar
{
    //  Original constructor
    int value { get; set; }
    public bar(int i)
    {
        this.value = i;    
    }       
}

public abstract class foobar : bar
{
    int value {get; set;}
    protected foobar(int i) : base(i)
    {
      value = i;
    }        
}

public class foo : foobar
{
    //  New constructor
    protected foo(int i)
        : base(i)
    {

    }
}


来源:https://stackoverflow.com/questions/12197106/calling-a-second-level-base-class-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!