简体   繁体   English

具有继承C#的多个构造函数

[英]Multiple constructors with inheritance c#

I have a base class B with multiple constructors. 我有一个带有多个构造函数的基类B。 I have a derived class D which has some additional fields to be set in its constructor(s), implemented as shown below. 我有一个派生类D,它的构造函数中还有一些其他字段需要设置,如下所示。

B(args1) {...}
B(args2) {...}
...
B(argsN) {...}

D(args1, additional) : B(args1) {...}
D(args2, additional) : B(args2) {...}
...
D(argsN, additional) : B(argsN) {...}

Problem is, every time a new B constructor is added with new args I have to make a new D constructor. 问题是,每次使用新的args添加新的B构造函数时,我都必须创建新的D构造函数。 Any way around this? 可以解决吗?

You have to define a constructor in the derived class if you want it in the base class and expect them to be identical. 如果要在基类中使用构造函数,并希望它们相同,则必须在派生类中定义一个构造函数。 You could, however, use default values as suggested. 但是,您可以按照建议使用默认值。 Or, have a dictionary-based constructor, which derived classes grab values from. 或者,有一个基于字典的构造函数,派生类从中获取值。

Could you use an alternative design pattern like Factory Method, Factory, or something to simplify the constructor approach? 您可以使用替代设计模式(例如“工厂方法”,“工厂”)来简化构造方法吗?

If you really want constructors and want to add a complicated solution, use the following. 如果您确实想要构造函数并想要添加复杂的解决方案,请使用以下内容。 NOT RECOMMENDING IT, but you could use code sharing/generation technique with a combination of partial classes (define one partial class with the constructors, and the other has all of the properties/members/etc.) and in that partial class that has the constructors, a T4 template overwrites it when the base template changes. 不建议这样做,但是您可以将代码共享/生成技术与部分类组合使用(使用构造函数定义一个部分类,而另一个具有所有的属性/成员/等),并且在该部分类中具有构造函数时,T4模板会在基础模板更改时覆盖它。 Again, this adds A LOT of overhead... I don't know how many classes you are talking about, and how exact you want them. 再次,这增加了很多开销...我不知道您正在谈论多少类,以及您希望它们有多精确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM