我们如何从调用基类中的另一方法的虚方法,即使当前实例是一个派生类的? [英] How do we call a virtual method from another method in the base class even when the current instance is of a derived-class?

查看:257
本文介绍了我们如何从调用基类中的另一方法的虚方法,即使当前实例是一个派生类的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何从另一个调用方法,即使当前实例是一个派生类的基类的虚方法?



我知道我们可以称之为< STRONG>方法2 在基本导出类中的方法类使用的 base.Method2()但我想要做的就是从在基本类中的其他虚拟方法调用它。 ?是否有可能

 使用系统; 

命名ConsoleApplication1
{
类节目
{
静态无效的主要(字串[] args)
{
碱乙=新的派生();
b.Method1();
}
}


公共类基地
{
公共虚拟无效方法1()
{
控制台.WriteLine(方法一中的基类。);
this.Method2(); //我想这条线始终调用方法二基类,即使当前实例是一个派生类对象。
//我想'这'在这里总是指基类。是否可以?
}

公共虚拟无效方法2()
{
Console.WriteLine(方法二中的基类。);
}
}

公共类派生:基本
{
公共覆盖无效方法1()
{
Console.WriteLine (方法1中派生的类。);
base.Method1();
}

公共覆盖无效的方法2()
{
Console.WriteLine(方法二中派生的类。);
}
}

}



随着上面的代码,它会输出:

 方法1中派生的类。 
方法一中的基类。
方法2中派生的类。



而我会想到的是:



 方法1中派生的类。 
方法一中的基类。
方法2中的基类。


解决方案

没有你不能做到这一点,虚拟方法的目的是派生类可以覆盖的执行和从基类被调用时执行甚至使用。



如果导致问题,那么你需要运行不应该在一个虚拟的方法的代码。


How do we call a virtual method from another method in the base class even when the current instance is of a derived-class?

I know we can call Method2 in the Base class from a method in the Derived class by using base.Method2() but what I want to do is calling it from the other virtual method in the Base class. Is it possible?

using System;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main( string[] args )
    {
      Base b = new Derived(  );
      b.Method1(  );
    }
  }


  public class Base
  {
    public virtual void Method1()
    {
      Console.WriteLine("Method1 in Base class.");
      this.Method2( );   // I want this line to always call Method2 in Base class, even if the current instance is a Derived object.
      // I want 'this' here to always refer to the Base class. Is it possible?
    }

    public virtual void Method2()
    {
      Console.WriteLine( "Method2 in Base class." );
    }
  }

  public class Derived : Base
  {
    public override void Method1()
    {
      Console.WriteLine( "Method1 in Derived class." );
      base.Method1();
    }

    public override void Method2()
    {
      Console.WriteLine( "Method2 in Derived class." );
    }
  }

}

With the above codes, it will output:

Method1 in Derived class.
Method1 in Base class.
Method2 in Derived class.

while what I would expect is:

Method1 in Derived class.
Method1 in Base class.
Method2 in Base class.

解决方案

No you cannot do that, the purpose of virtual methods is that derived classes can override the implementation and that the implementation is used even when called from base classes.

If that causes problems then the code you need to run should not be in a virtual method.

这篇关于我们如何从调用基类中的另一方法的虚方法,即使当前实例是一个派生类的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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