C# - 让所有派生类都调用基类构造函数 [英] C# - Making all derived classes call the base class constructor

查看:35
本文介绍了C# - 让所有派生类都调用基类构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类 Character,它有几个派生自它的类.基类有各种字段和方法.

I have a base class Character which has several classes deriving from it. The base class has various fields and methods.

我的所有派生类都使用相同的基类构造函数,但如果我不在派生类中重新定义构造函数,则会出现错误:

All of my derived classes use the same base class constructor, but if I don't redefine the constructor in my derived classes I get the error:

错误:类子类"不包含接受此数量参数的构造函数

我不想在每个派生类中重新定义构造函数,因为如果构造函数发生变化,我必须在每个类中更改它,请原谅任何误解,这与只编写一次代码的想法背道而驰?

I don't want to redefine the constructor in every derived class because if the constructor changes, I have to change it in every single class which, forgive any misunderstanding, goes against the idea of only writing code once?

推荐答案

确实必须重新声明构造函数,因为它们实际上并未被继承.如果您认为构造函数在某些方面有点像静态方法,那是有道理的.

You do have to redeclare constructors, because they're effectively not inherited. It makes sense if you think of constructors as being a bit like static methods in some respects.

特别是,你不会希望自动继承所有的构造函数——毕竟,这意味着每个类都有一个无参数的构造函数,如object 本身就可以.

In particular, you wouldn't want all constructors to be automatically inherited - after all, that would mean that every class would have a parameterless constructor, as object itself does.

如果您只想调用基类构造函数,则无需在构造函数主体中编写任何代码 - 只需按照 Waleed 的帖子将参数传递给基类即可.

If you just want to call the base class constructor though, you don't need to write any code in the body of the constructor - just pass the arguments up to the base class as per Waleed's post.

如果您的基类开始需要更多信息,那么您很自然地应该更改所有派生类——实际上是任何调用这些类的构造函数的东西——因为它们必须提供信息.我知道这看起来很痛苦,但这只是构造函数的自然结果.

If your base class starts requiring more information, it's natural that you should have to change all derived classes - and indeed anything calling the constructors of those classes - because they have to provide the information. I know it can seem like a pain, but it's just a natural consequence of what constructors do.

这篇关于C# - 让所有派生类都调用基类构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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