开发者

Why is the base() constructor not necessary?

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?


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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜