作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在具有抽象类类型的对象上调用子类实现。但是,这并不像我想象的那样有效。有没有办法做到这一点,不需要我在第二个切换语句中切换类型?还是 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.
}
}
virtual
和 abstract
的区别在于,基本上,abstract
方法不能有一个基础实现,并且必须被覆盖。
虚拟
方法可以有一个基础实现,不需要被覆盖。
您不需要调用 base.MethX/Y()
。如果愿意,您甚至可以赋予该方法全新的含义。
关于c# - 抽象类类型C#的调用子实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49852666/
我是一名优秀的程序员,十分优秀!