Is it possible to override a constructor in C#?

假装没事ソ 提交于 2019-12-17 10:52:16

问题


Is it possible to override the constructor of the base class in the derived class?

If so, the how can it be accomplished and in what use case would this be practical? If not, why not?


回答1:


No, you can't override constructors. The concept makes no sense in C#, because constructors simply aren't invoked polymorphically. You always state which class you're trying to construct, and the arguments to the constructor.

Constructors aren't inherited at all - but all constructors from a derived class must chain either to another constructor in the same class, or to one of the constructors in the base class. If you don't do this explicitly, the compiler implicitly chains to the parameterless constructor of the base class (and an error occurs if that constructor doesn't exist or is inaccessible).




回答2:


No, Constructors are not inherited. You can not override them in derived class.
Reason

A base constructor will always be called, for every class that descends from object, because every class must have at least one constructor that calls a base() constructor (explicitly or implicitly) and every call to a this() constructor must ultimately call a base() constructor.




回答3:


No, you can't override the constructor.

If you take a look at the basic syntax of a constructor, it should have the same name as the class you are writing it for.

Lets say,you write a method with the same name as that of the base class(same as that of base class constructor), its just gonna be a new method in the derived class without return type specified, which is syntactically incorrect.



来源:https://stackoverflow.com/questions/11271920/is-it-possible-to-override-a-constructor-in-c

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