【问题标题】:Is there a way to call super's super in C#有没有办法在 C# 中调用 super 的 super
【发布时间】:2012-12-05 13:26:40
【问题描述】:

我知道这是糟糕的设计,我只是有点懒得检查代码,我宁愿走捷径。

class Grandma
{
   public virtual void Mtd(){}
}

class Mommy : Grandma
{
   public override void Mtd(){ base.Mtd(); /* other stuff I wanna skip*/}
}

class Daughter : Mommy
{
   public override void Mtd(){ /*base.base.Mtd() //How can I do it ? */}
}

因为这个方法是虚拟的upcast 是行不通的。那么,这可能吗?

【问题讨论】:

标签: c# polymorphism base


【解决方案1】:

这是不可能的;但是,如果你想走捷径,你可以在 Mommy 方法中添加一个类型检查:

class Mommy : Grandma
{
    public override void Mtd()
    { 
        base.Mtd();   // calls `Grandma` implementation

        if (this.GetType() == typeof(Mommy))
        {
            // not executed for any derived class
        }

        if (!(this is Daughter))
        {
            // not executed for `Daughter`
        }
    }        
}

class Daughter : Mommy
{
    public override void Mtd()
    { 
        base.Mtd();   // calls `Mommy` implementation
    }
}

【讨论】:

  • 但这会使 Mommy 类与 Daughter 类紧密耦合,我认为这是不好的做法;)
  • 我添加了this.GetType() == typeof(Mommy) 的替代检查,它将排除所有派生类,而不仅仅是Daughter。当然,正如您所要求的,这仍然是“黑客”;正确的解决方案可能是重构您的代码(通过引入布尔参数或拆分方法层次结构)。
【解决方案2】:

无法“跳过”Mommy 覆盖。 您必须以某种方式对其进行重构。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-19
    • 2022-07-15
    • 2015-09-16
    • 1970-01-01
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    相关资源
    最近更新 更多