【问题标题】:Is it possible to access base class virtual method by derived class object, even though the same virtual method is overridden in the derived class? [duplicate]即使在派生类中重写了相同的虚拟方法,是否可以通过派生类对象访问基类虚拟方法? [复制]
【发布时间】:2016-03-31 09:23:32
【问题描述】:
namespace AbstractImplementation
{
    public class baseclass 
    {
        public virtual void testingSealed()
        {
            Console.WriteLine("This is testingSealed base");
        }
    }


    public class derived : baseclass
    {
        public override void testingSealed()
        {
            Console.WriteLine("This is testing derived");
        }

    }

  class Program
    {
        static void Main(string[] args)
        {
            derived der = new derived();
            der.testingSealed(); 

        }
    }
}

这将给出“这是测试派生”的输出。是否可以从 der.testingSealed() 获取“This is testingSealed base”?

【问题讨论】:

  • 如果要获取基本消息,为什么不实例化基本类型呢?对我来说,这听起来像是XY 的问题。
  • 要访问 baaeclass 方法,您必须创建基类的对象。在派生类中重写基类对象时,无法访问它。
  • 这个问题是在一次采访中问我的。在这种情况下,我给出了 2 个答案。 1)如果我们要访问基类,不需要重写派生类中的方法 2)创建基类对象并访问该方法。但是他说有一些方法可以通过派生类对象访问在派生类中被覆盖的基类方法,当我问这个问题的答案时,他让我找出来。
  • 对虚拟非密封方法使用call MSIL 指令仅当调用实例为this 时才被认为是可验证的,因此,它只能来自内部对象,而不是来自外部代码。

标签: c#


【解决方案1】:

您可以使用 base 关键字从派生类访问基方法:

public class BaseClass
{
    public virtual void TestingSealed()
    {
        Console.WriteLine("This is testingSealed base");
    }
}


public class Derived : BaseClass
{
    public override void TestingSealed()
    {
        base.TestingSealed(); // here
        Console.WriteLine("This is testing derived");
    }

    public void TestingSealedBase()
    {
        base.TestingSealed(); // or even here
    }
}

var der = new Derived();
der.TestingSealed();
der.TestingSealedBase();

这将输出:

This is testingSealed base.
This is testing derived.
This is testingSealed base.

附:请,C# 命名约定要求类和方法以 UpperCamelCase 命名。

【讨论】:

  • 使用 base 我们可以做到。但是这里我们没有实例化对象。我们必须通过实例化派生类来调用base。
  • @user1722137 - 你能更详细地解释你的评论吗?
【解决方案2】:

一旦派生类被实例化,就不能在基类中调用虚方法。如果您必须调用虚方法,则说明您的设计存在缺陷。

看到这个帖子: How can I call the 'base implementation' of an overridden virtual method?

但是,您可以从被覆盖的方法中调用虚拟方法:

public override void testingSealed()
    {
        base.testingSealed();
        Console.WriteLine("This is testing derived");
    }

【讨论】:

  • 明白。谢谢
【解决方案3】:

只是不要覆盖派生类中的方法。

【讨论】:

  • 最好在不发布任何代码时添加评论
  • 这是该问题的第一个正确答案,不需要任何代码。如果更多人不发布无关紧要的内容,世界将会变得更美好。
猜你喜欢
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多