是否可以在 C# 中覆盖构造函数? [英] Is it possible to override a constructor in C#?

查看:30
本文介绍了是否可以在 C# 中覆盖构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在派生类中重写基类的构造函数?

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?

推荐答案

不,您不能覆盖构造函数.这个概念在 C# 中没有意义,因为构造函数根本不是多态调用的.你总是说明你试图构造哪个类,以及构造函数的参数.

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

这篇关于是否可以在 C# 中覆盖构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆