在 C# 中,子类对象如何直接调用被覆盖的超类方法? [英] In C# how can a sub class object can directly call a super class method which is overridden?

查看:110
本文介绍了在 C# 中,子类对象如何直接调用被覆盖的超类方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天在 C# 中学习了一些 OOP 概念,在学习的过程中我发现一个子类 Object 能够直接从其被覆盖的超类调用一个方法,我熟悉 Java,其中如果一个方法被其覆盖超类,如果子类对象正在调用相同的方法,则执行子类中存在的方法,而不是执行我们使用super"关键字的超类方法.

I was learning some OOP concept in C# today and while learning i found that a sub class Object is able to call a method directly from its super class which is overridden, i am familiar with Java in which if a method is overridden from its super class and if a sub class object is calling the same method then the one which is present in a sub class is executed and not the super class method to do that we use "super" keyword.

我的问题是C#如何提供这样的特性,直接允许子类对象执行被覆盖的超类方法

My Que is how does C# provide such feature that directly allows a sub class object to execute the super class method which is overridden

下图是子类对象obj"允许我使用的代码通过提供选项void Super.display"来调用超类方法显示

The below image is the code in which the sub class object "obj" allows me to call the super class method display by giving an option "void Super.display"

推荐答案

从图片上看,你没有override基类的方法,而是隐藏方法.

From the image, you haven't override the method from base class, instead you are hiding the method.

使用方法隐藏,您不能像屏幕截图中那样从子类调用基类方法:

With method hiding you can't call base class method from the child class like in the screen shot you have:

来自屏幕截图的代码.

Sub obj = new Sub();
obj.display();// this will call the child class method

intellisence 中对 Super.display 的引用可能有问题,您不能像那样从基类调用隐藏方法.

The reference to Super.display in intellisence is probably buggy, you can't call a hidden method from the base class like that.

(由于方法隐藏,您还应该收到警告使用 new 关键字)

要实现适当的覆盖,您在基类中的方法必须是 virtualabstract,例如:

To achieve a proper override, your method in base class has to be virtual or abstract like:

public class Super
{
    public virtual void display()
    {
        Console.WriteLine("super/base class");
    }
}

public class Sub : Super
{
    public override void display()
    {
        Console.WriteLine("Child class");
    }
}

然后你可以这样称呼它:

and then you can call it like:

Super obj = new Sub();
obj.display(); //child class

Super objSuper = new Super();
objSuper.display(); //base class method

如果要从子类内部调用基类方法,请使用 base 关键字,例如:

If you want to call base class method from inside the child class then use the base keyword like:

public override void display()
{
    base.display();
    Console.WriteLine("Child class");
}

这篇关于在 C# 中,子类对象如何直接调用被覆盖的超类方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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