是否可以覆盖 C# 中的构造函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11271920/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to override a constructor in C#?
提问by naval
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?
如果是这样,它如何实现以及在什么用例中这将是实用的?如果没有,为什么不呢?
采纳答案by Jon Skeet
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.
不,您不能覆盖构造函数。这个概念在 C# 中没有意义,因为构造函数根本不是多态调用的。你总是说明你试图构造哪个类,以及构造函数的参数。
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).
构造函数根本不会被继承——但是派生类的所有构造函数都必须链接到同一类中的另一个构造函数,或者链接到基类中的一个构造函数。如果不显式执行此操作,编译器会隐式链接到基类的无参数构造函数(如果该构造函数不存在或不可访问,则会发生错误)。
回答by Shezi
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.
对于每个继承自对象的类,总是会调用基构造函数,因为每个类都必须至少有一个调用 base() 构造函数(显式或隐式)的构造函数,并且每次调用 this() 构造函数最终都必须调用一个base() 构造函数。
回答by Vizard
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.
假设您编写了一个与基类同名的方法(与基类构造函数的同名),它只是派生类中没有指定返回类型的新方法,这在语法上是不正确的。

