调用抽象类类型 C# 的子实现

Han*_*ens 3 c# inheritance abstract

我想在具有抽象类类型的对象上调用子类实现。然而,这并不像我想象的那样工作。有没有办法做到这一点,不需要我在第二个 switch 语句中在类型之间切换?或者 C# 不允许这种类型的行为?

调用它的代码:

AbstractParentType wfp;

//Switch on diagram type and select processor
switch (qi.DIAGRAMTYPE)
{
    case 1:
        wfp = new T1(notifications);
        break;
    case 2:
        wfp = new T2(notifications);
        break;
    case 3:
        wfp = new T3(notifications);
        break;
    default:
        throw new Exception("Diagramtype not implemented");
}

bool result = false;
//Switch on action type
switch (qi.Type)
{
    case (int)WorkflowActionType.BelItem:
        //Do some case specific stuff here
        ...
        //Call method
        result = wfp.Meth1();
        break;
    ... (a bunch of cases) ...
    case (int)WorkflowActionType.WordDocument:
        //Do some case specific stuff here
        ...
        //Call method
        result = wfp.Meth10();
        break;
}
Run Code Online (Sandbox Code Playgroud)

然后我们有类的实现:

abstract class AbstractClassType {
     public bool Meth1() { ... }
     ...
     public bool Meth10() { ... }
     ...
     public abstract MethX();
     public abstract MethY();
}

class T1 : AbstractClassType  {
     public new Meth1() { ... }
     ...
     public new Meth10() { ... } 
     ...
     public override MethX() { ... }
     public override MethY() { ... }
}
Run Code Online (Sandbox Code Playgroud)

实际的方法确实有参数,我确实想要一些方法(但不是全部)的基本实现。目标是允许继承类“扩展”方法的行为。

Bak*_*een 6

尝试使用virtual关键字

使用 virtual 时,您可以为基类中的方法提供“默认”实现。就像这样:

abstract class AbstractClassType {
    public virtual void MethX(){
        //default implementation here.            
    }
    public virtual void MethY(){
        //another default implementation here!
    }
}

class T1 : AbstractClassType {
    public override void MethX(){
        //base.MethX() would call the logic in the base class. 
    }
    public override void MethY(){ 
        //base.MethY() would call the logic in the base class. 
    }
}
Run Code Online (Sandbox Code Playgroud)

virtual和之间的区别在于abstract,基本上,abstract方法不能有基本实现,并且必须被重写。

方法可以virtual有一个基本实现,并且不需要被重写。

您无需致电base.MethX/Y()。如果您愿意,您甚至可以赋予该方法全新的含义。