调用一个覆盖方法的祖父母实施 [英] Calling the grand-parent implementation of an overridden method

查看:156
本文介绍了调用一个覆盖方法的祖父母实施的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:结果
如何调用base.base.method()?






我有一些麻烦,在C#中继承。我已经勾勒三类: A B C C 继承乙 B A 。现在 B 调用类 base.Method1 和工作正常,但我不能叫 A .method1 C 类。如果我称之为 base.Method1 C 显然这种方法将是方法1 B 的。有什么建议?



P.S。在 A 类也有一些田标记为私有,所以你可以访问它们只能

  A级
{
私有实例;
公共虚拟无效方法1()
{
实例=这一点;
做一些事情;
}
}

B类:A
{
公共覆盖无效方法1()
{
base.Method1( );
做一些事情;
}
}

类C:B
{
公共覆盖无效方法1()
{
//有需要的方法1然后做什么
}
}


解决方案

这是C#的一个特点。如果您想公开这个方法来C类,考虑重构一个像这样:

  A级
{
私有的实例;
公共虚拟无效方法1()
{
AMethod1();
}

保护无效AMethod1()
{
实例=这一点;
做一些事情;
}
}

这将使你从C调用此方法

  C类:b 
{
公共覆盖无效方法1()
{
AMethod1();
//做一些事情;
}
}


Possible Duplicate:
How to call base.base.method()?

I have some trouble with Inheritance in C#. I've sketched three classes: A, B and C. C inherits from B and B from A. Now the B class calls base.Method1 and works fine but I can't call A.method1 from the C class. If I call base.Method1 from C obviously that method will be method1 of B. Any advice?

P.S. in A class there are some fields marked private so you can access them only

class A
{    
    private instance;    
    public virtual void Method1 ()
    {       
        instance = this;
        do something;       
    }
}

class B : A
{
    public override void Method1()
    {
        base.Method1();
        do something;       
    }
}

class C : B
{   
    public override void Method1 ()
    {
        //need A Method1 then do something
    }
}

解决方案

This is a feature of C#. If you wish to expose this method to class C, consider refactoring A like so:

class A
{    
  private instance;    
  public virtual void Method1 ()
  {
    AMethod1();       
  }

  protected void AMethod1()
  {
    instance = this;
    do something;       
  }
}

This will enable you to call this method from within C:

class C : B
{   
  public override void Method1 ()
  {
    AMethod1();
    // do something;
  }
}

这篇关于调用一个覆盖方法的祖父母实施的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆