c# - 是否可以通过派生类对象访问基类虚方法,即使在派生类中重写了相同的虚方法?

标签 c#

<分区>

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(); 

        }
    }
}

这将给出输出“This is testing derived”。是否可以从 der.testingSealed() 获取“This is testingSealed base”?

最佳答案

您可以使用 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 命名。

关于c# - 是否可以通过派生类对象访问基类虚方法,即使在派生类中重写了相同的虚方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34461138/

相关文章:

c# - ASP.NET MVC 中的异步 GET/POST 和操作名称冲突

c# - 使用 nHibernate 实体和 DTO 发送网格数据

c# - 动态数组 |展开对象 |使用压缩的初始化语法

c# - 如何识别仍然引用对象实例的位置?

c# - 非静态字段、方法或属性(数据集)需要对象引用

c# - 属性构造函数不能使用 console.writeline

c# - Epplus:如何使 "LoadFromCollection"在模型中使用 [DisplayFormat()] 属性

c# - 我应该在 MMORPG 模拟器中使用指针吗?

c# - XML XPath 问题

c# - 如何在 GridLookUpEdit 中隐藏零?