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

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

问题描述

我有一个基类角色有哪几种类从中获得。该基类有不同的属性和方法。

我所有的派生类中使用相同的基类的构造函数,但如果我没有在我的派生类中重新定义构造函数我得到的错误:

错误:类子类不包含一个构造函数,采用此数目的参数

我不想重新定义构造函数在每一个派生类中,因为如果构造的变化,我不得不改变它在每一个类,原谅任何误解,违背了只写code曾经的想法?


解决方案

您的的要重新定义构造函数,因为他们不能有效继承。这是有道理的,如果你想构造器作为一个有点像在某些方面的静态方法。

在特定的,你不会的希望的所有构造函数将自动继承 - 毕竟,这将意味着的每个的类将有一个参数的构造函数,如对象本身一样。

如果你只是想虽然调用基类的构造函数,你不需要编写任何code在构造函数体 - 只是传递参数到基类按瓦利德的帖子

如果你的基类开始需要更多的信息,这是自然的,你应该改变所有派生类 - 实际上任何调用这些类的构造函数 - 因为他们要的提供的信息。我知道这似乎是一个痛苦,但它是一个什么样的构造做只是一个自然的结果。

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:

Error: Class "child class" doesn't contain a constructor which takes this number of arguments

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.

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.

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天全站免登陆