【问题标题】:How to access the previous parents in the inheritance hierarchy in C# [duplicate]如何在 C# 中访问继承层次结构中的先前父级 [重复]
【发布时间】:2015-02-10 06:34:28
【问题描述】:

我只是想了解以下是否可行。

我有 customer、specialCustomer 和 goldCustomer 类。 Special 继承自 Customer,GoldCustomer 继承自 SpecialCustomer。

如何从 GoldCustomer 访问 Customer 类的 Add() 实现?使用 base.Add() 只调用直接父级的 Add()

public class Customer
{
    public virtual void add()
    {
        Console.WriteLine("Base Add");

    }
}

public class SpecialCustomer: Customer
{
    public override void add()
    {            
        Console.WriteLine("SPL CUST Add");
    }
}

public class GoldCustomer : SpecialCustomer
{

    public new void add()
    {
        base.add();// cals the immediate parent.
        //How to call the method on Customer base class(Parent's parent)
        Console.WriteLine(" chid GOLD CUST Add");
    }

}

【问题讨论】:

    标签: c# inheritance


    【解决方案1】:

    我的第一个建议是尽可能避免这种情况(软件很复杂,为什么要让它变得更复杂?)。

    第二个建议,如果您无法避免这种情况,将this 转换为所需的基本类型并调用所需的方法,例如((Customer)this).add()

    但是你能解释一下为什么你需要做这种事情吗?可能是您的设计需要重构。

    【讨论】:

      【解决方案2】:
          public class Customer
          {
              public virtual void add()
              {
                  C1();
              }
      
      
              public void C1()
              {
                  Console.WriteLine("Base Add");
              }
          }
      

      您的代码应如下所示,然后调用new GoldCustomer.C1();

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-22
        • 1970-01-01
        • 1970-01-01
        • 2011-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多