简体   繁体   English

C# 抽象 class 设计,是否可以在抽象 class 中放置一个构造函数并调用基础来访问它们

[英]C# abstract class desgin, is that possible put a constuctor in abstract class and call base to access them

I was practicing c# abstract class and inheritance, but I was wondering if derived classes could access the constructor by calling the base我在练习 c# abstract class 和 inheritance,但我想知道派生类是否可以通过调用基类来访问构造函数

public abstract class A
{
    protected bool value_A;
    protected int value_B;
    public A(int input)
    {
      A = true;
      B = false;
    }
    public abstract int function_B();
  }

}
public class childA : A
{
    public childA (int input):base(input)
    { 
    }
    public override int function_B()
    {
      //do smth
    }   
}
public class childB : A
{
    public childB(int input):base(input)
    {   
    }
    public override int function_B()
    {
      //do something different
    }
    public void functionC(int input)
    {
        
    }   
}

I was confused if I should use this abstract class design or just go ez by using inheritance -> declare a virtual function in class A. I was confused if I should use this abstract class design or just go ez by using inheritance -> declare a virtual function in class A.

  1. Yes, you can.是的你可以。 Derived class c'tor can call base class one, even if the base class is abstract.派生的 class c'tor 可以调用基础 class 之一,即使基础 class 是抽象的。
  2. Generally, using abstract base class makes sense if there is a common functionality (or traits) that you want to reuse, and instantiating the base class does not make sense (and therefore you make it an abstract class).通常,如果您想要重用一个通用功能(或特征),则使用抽象基 class 是有意义的,并且实例化基 class 没有意义(因此您将其设为抽象类)。 A basic example is "Shapes" hierarchy, with abstract base class Shape that has color and center (for instance) and virtual method Draw, and all specific shapes inheriting from Shape and implementing the actual Draw functionality for each specific shape.一个基本示例是“形状”层次结构,具有抽象基础 class 形状,该形状具有颜色和中心(例如)和虚拟方法 Draw,所有特定形状都继承自 Shape 并为每个特定形状实现实际的 Draw 功能。

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

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