gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 15:00:49 25 4
gpt4 key购买 nike

我想在具有抽象类类型的对象上调用子类实现。但是,这并不像我想象的那样有效。有没有办法做到这一点,不需要我在第二个切换语句中切换类型?还是 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;
}

然后我们有类实现:

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() { ... }
}

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

最佳答案

尝试使用 virtual keyword

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

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.
}
}

virtualabstract 的区别在于,基本上,abstract 方法不能有一个基础实现,并且必须被覆盖。

虚拟方法可以有一个基础实现,不需要被覆盖。

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

关于c# - 抽象类类型C#的调用子实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49852666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com