c# - 使用 new 关键字中断虚拟调用并再次启动新的虚拟层次结构

标签 c# inheritance polymorphism virtual overriding

这是我混淆的代码。

 class foo
{
    public string fname;
    public virtual void print()
    {
        Console.WriteLine("I am the boss i am the virtual");
    }
};


class bar : foo 
{

    public override void print()
    {
        Console.WriteLine("I am the first derivative");   
    }
};


class tar : bar
{
    public new virtual void print()
    {

        Console.WriteLine("I am the newly born baby with a new keyword!!!!");
    }

};


class jar : tar
{
    public override void print()
    {
        Console.WriteLine("i am created in derivative of tar i.e, jar");

    }

};  
class Program
{
    static void Main(string[] args)
    {
        foo obj1 = new foo();
        obj1.fname = "neha";

        foo objtar = new jar();  //here lies the confusion why bar print() is called   
        objtar.print();
    }
}

在此代码中,我使用第 3 级派生类 (jar) 对象和基类 (foo) 调用打印方法。查看输出结果我感到很困惑

I am the first derivative

谁能解释一下背后的原因。我是 c# 的新手,需要帮助....

最佳答案

那是因为您在 foo 的实例上调用了 printnew 关键字将仅应用于该类型的类型化实例。

继承规则不再适用,因为 tar.print新的

这是所有记录在案的行为,您可以在 MSDN 上找到.

所以这将按您的预期工作:

jar objtar = new jar();
objtar.print();

关于c# - 使用 new 关键字中断虚拟调用并再次启动新的虚拟层次结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25140044/

相关文章:

c# - 关闭程序后重新启动应用程序

c# - 从 .DLL 获取位图,转换为 byte[] 和图像

c# - DropDownCheckBoxes 不响应 ASP.NET 中的 Bootstrap 类

c++ - 从基类构造函数调用派生类的成员函数

scala - Scala中的家庭多态性

C++基类指针、集合类

c# - .NET 反射 : Unable to retrieve Dynamic Properties

c# - 向下转换泛型参数时如何修复转换错误

c++ - 我们可以声明一个抽象方法来返回抽象父类(super class)中的子类对象而无需新的实例化吗?

c++ - 无重复代码的多态函数调用