如何调用重写的虚拟方法的“基本实现"? [英] How can I call the 'base implementation' of an overridden virtual method?

查看:23
本文介绍了如何调用重写的虚拟方法的“基本实现"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下代码,有没有一种方法可以调用 A 类版本的方法 X?

Given the following code, is there a way I can call class A's version of method X?

class A
{
  virtual void X() { Console.WriteLine("x"); }
}

class B : A
{
  override void X() { Console.WriteLine("y"); }
}

class Program
{
  static void Main()
  {
    A b = new B();
    // Call A.X somehow, not B.X...
  }

推荐答案

使用 C# 语言结构,您不能从 A 作用域的外部显式调用基函数或 B.如果您真的需要这样做,那么您的设计就存在缺陷 - 即该函数一开始就不应该是虚拟的,或者应该将基函数的一部分提取到一个单独的非虚拟函数中.

Using the C# language constructs, you cannot explicitly call the base function from outside the scope of A or B. If you really need to do that, then there is a flaw in your design - i.e. that function shouldn't be virtual to begin with, or part of the base function should be extracted to a separate non-virtual function.

您可以从内部 B.X 但是调用 A.X

You can from inside B.X however call A.X

class B : A
{
  override void X() { 
    base.X();
    Console.WriteLine("y"); 
  }
}

但那是另一回事.

正如 Sasha Truf 在这个答案中指出的那样,您可以通过 IL 来完成.正如 mhand 在评论中指出的那样,您可能也可以通过反射来完成它.

As Sasha Truf points out in this answer, you can do it through IL. You can probably also accomplish it through reflection, as mhand points out in the comments.

这篇关于如何调用重写的虚拟方法的“基本实现"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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