Why is the base() constructor not necessary?

亡梦爱人 提交于 2019-12-22 04:34:15

问题


I have a class structure like

abstract class Animal {
  public Animal(){
    //init stuff..
  }
}

class Cat : Animal {
  public Cat(bool is_keyboard) : base() //NOTE here
  {
    //other init stuff
  }
}

Now then, look at the noted line. If you remove : base() then it will compile without an error.

Why is this? Is there a way to disable this behavior?


回答1:


There is an implicit : base() if you don't add anything else (any : base(...) or : this(...)). To force it to be explicit, add a parameter to the base-constructor(s). Then it can't be implicit.

For example:

public Animal(string name) {...}



回答2:


17.10.4 Default Constructors:

If a class contains no instance constructor declarations, a default instance constructor is automatically provided. 2 That default constructor simply invokes the parameterless constructor of the direct base class. 3 If the direct base class does not have an accessible parameterless instance constructor, a compile-time error occurs. 4 If the class is abstract then the declared accessibility for the default constructor is protected. 5 Otherwise, the declared accessibility for the default constructor is public




回答3:


Why is this?

This article explains it.

Is there a way to disable this behavior?

Nope. I'm sorry (but ... See mark answer for a workaround : )



来源:https://stackoverflow.com/questions/2556410/why-is-the-base-constructor-not-necessary

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