简体   繁体   English

在C#中省略子类构造函数的参数

[英]Omitting a subclass constructor's arguments in C#

Say I have an abstract superclass, A , which is defined as: 假设我有一个抽象超类A ,其定义为:

public abstract class A {
    protected string a1;
    protected int a2;
    protected char a3;

    public A(string a1, int a2, char a3) {
        this.a1 = a1;
        this.a2 = a2;
        this.a3 = a3;
    }
}

I then have x classes that inherit from A -- each using the same constructor -- but each have their own methods which use a1, a2, and a3 in their own unique ways. 然后,我有了x个从A继承的类-每个类都使用相同的构造函数-但每个类都有自己的方法,这些方法以各自独特的方式使用a1,a2和a3。 Despite the constructors being the same, from what I understand I'd have to re-define the number and type of arguments in each subclass like so: 尽管构造函数相同,但据我了解,我必须重新定义每个子类中参数的数量和类型,如下所示:

public sub(string a1, int a2, char a3) : base(a1, a2, a3) {}

This could be a pain if I need to change the type of arguments, because I'd need to tweak all 11 classes. 如果我需要更改参数类型,可能会很痛苦,因为我需要调整所有11个类。 If I'm using good inheritance practices, in most cases all classes should be affected anyway if I modify the parameters of A 's constructor, but there are some instances where this isn't true. 如果我使用良好的继承做法,那么在大多数情况下,如果我修改A的构造函数的参数,所有类都将受到影响,但是在某些情况下,这是不正确的。 For instance, if I change a parameter from type Vehicle to Car . 例如,如果我将参数从Vehicle类型更改为Car Car is a subclass of Vehicle , so it has all of Vehicle 's API members, and none of the classes would need changing, aside from their constructor. CarVehicle的子类,因此它具有Vehicle的所有API成员,除其构造函数外,无需更改任何类。

Is there any way to do something along the lines of: 有什么办法可以做以下事情:

public sub {
    public sub(...) : base(...) {}
}

so that there's no need to change all 10 subclass constructor definitions when an argument type changes? 这样,当参数类型更改时,就不需要更改所有10个子类构造函数定义了吗?

No, there is no syntactic sugar for it. 不,没有语法糖。

You can wrap all parameters in a class so changes to parameters will not impact all types, but you can easily miss handling of newly added parameters: 您可以将所有参数包装在一个类中,因此对参数的更改不会影响所有类型,但是您很容易错过对新添加的参数的处理:

class ConstructorParams 
{ 
  public int a {get;set;}
} 

...
public Base( ConstructorParams p) {...}
...
public Sub(ConstructorParams p) : Base(p) {}

Note that using refactoring tools in VS (and external like R#) makes changes to method/constructor's arguments mostly automatic - so may be good idea to try those first before packing all parameters into single class. 请注意,在VS中使用重构工具(和外部的R#一样)使对方法/构造函数的参数的更改基本上是自动进行的-因此在将所有参数打包到单个类中之前先尝试一下这些方法可能是个好主意。

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

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