简体   繁体   English

在C#中使用抽象子类的基类?

[英]Base class with abstract subclasses in C#?

public abstract class Request
{
   public class Parameters
   {
       //Threre are no members here
       //But there should be in inherited classes
   }

   public Request()
   {
       parameters = new Parameters();
   }

   public Parameters parameters;
}

Two questions: 两个问题:

  1. How do I make it so I can add stuff to the constructor but the original constructor will still be executed? 我怎么做到这样我可以添加东西给构造函数但原始构造函数仍然会被执行?

  2. How do I make it so the subclasses can add members to the Parameters class? 如何使子类可以将成员添加到Parameters类?

If you're doing what I think you are you would have to change your constructor slightly: 如果你正在做我认为你的事情,你将不得不稍微改变你的构造函数:

public Request(Parameters parameters) {
  this.Parameters = parameters;
}

and then you can do this: 然后你可以这样做:

public class SpecificRequest : Request {
  public class SpecificRequestParameters : Request.Parameters {
  }
  public SpecificRequest() : base(new SpecificRequestParameters()) {
    //More stuff here
  }
}

What's the specific problem that you're trying to address? 您要解决的具体问题是什么? What you're doing here seems fairly awkward and overly complicated. 你在这里做的事情看起来相当尴尬和过于复杂。

Why do you embed the Parameters class inside the Request class? 为什么要在Request类中嵌入Parameters类? Instead, let Request have an instance of parameters and just declare the class somewhere else. 相反,让Request有一个参数实例,只需在其他地方声明该类。

Answer for your question 1: Inherit from Request and the original request constructor will always be called. 您的问题的答案1:从Request继承并始终调用原始请求构造函数。

Question 2: Subclasses cannot add members to parameter classes (except with reflection, but you dont want to walk that path). 问题2:子类不能将成员添加到参数类(除了反射,但你不想走这条路径)。 Best you can do is inherit from parameter and have the InheritedRequest use the InheritedParameter class. 您可以做的最好是从参数继承并让InheritedRequest使用InheritedParameter类。 Note that in that case you cannot override the properties and properties. 请注意,在这种情况下,您无法覆盖属性和属性。 You will have to have an additional property in InheritedRequest called AdditionalParameters of type InheritedParameters. 您必须在InheritedRequest中有一个名为AdditionalParameters类型为Additional InheritedParameters的附加属性。

Constructors can be chained with the syntax 构造函数可以使用语法链接

ctor() : this()

or 要么

ctor() : base()

in there you can pass parameters along etc. 在那里你可以传递参数等。

Make the Parameters field generic 使参数字段通用

abstract class Request<T> where T : Parameters {
  T Parameters;
}

class Specialized : Request<SpecialParameters> {
}

where SpecialParameters inherits from Parameters . 其中SpecialParameters继承自Parameters

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

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