简体   繁体   English

C#可能在抽象类中具有构造函数?

[英]C# possible to have a constructor in an abstract class?

I have 1 abstract class that is calling a static method which up until now didn't require any parameters. 我有1个抽象类正在调用一个静态方法,到目前为止,该方法不需要任何参数。 This has recently changed. 这最近改变了。 In reality the static method exists in another class and sets the value of BaseMessageDirectory, but in this example below I have simplified things... 实际上,静态方法存在于另一个类中并设置BaseMessageDirectory的值,但是在下面的示例中,我简化了事情……

So now I want to create my derived classes in such a way that they can initialize some required properties in the parent class during the inheritance, is this possible? 因此,现在我想以这样的方式创建派生类,使其可以在继承期间初始化父类中的某些必需属性,这可能吗?

For example.... 例如....

 public abstract class ParentClass
    {
          protected string BaseMessageDirectory;

          protected ParentClass(EnumOperationType operationType)
             {
                if(operationtype == 1)
                  {
                     BaseMessageDirectory = "one";
                  }
                else
                  {
                     BaseMessageDirectory = "two";
                  }
             }
    }

Yes, you can define a constructor, and all child classes will have to call it: 是的,您可以定义一个构造函数,所有子类都必须调用它:

public class Child : ParentClass
{
    public Child() : base(EnumOperationType.One) { ... }
}

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

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