简体   繁体   English

在C#中调用派生类ovverridden函数

[英]Calling a Derived class ovverridden function in c#

I have a class which is used as parent class and it has c () function which i want to override in derived class but the base class c function is getting called. 我有一个用作父类的类,它具有c()函数,我想在派生类中重写它,但是调用了基类c函数。 Here is the pseudo code for my class.may be this keyword is giving it a different meaning whole together 这是我班的伪代码。可能是这个关键字给了它整体一个不同的含义

public Class BaseRepository
{
    public A()
    {
        this.c();
    }

    public B()
    {
        this.c();
    }

    protected virtual c()
    {
        enter code here
    }
}

when i derive this class 当我上这堂课时

class customRepo:BaseRepository
{
    protected override c()
    {
        ...does something
    }
}

My custom repo function is not using the c() from custom repo class but the base repo class function is being used. 我的自定义回购函数未使用自定义回购类中的c() ,但正在使用基本回购类函数。 Can anyone tell me why this is happening ??? 谁能告诉我为什么会这样吗?

The most likely (and only I can come up with) reason this would be happening is that you instantiated a BaseRepostiory instead of a customRepo object. 发生这种情况的最可能的原因(也是我唯一能想到的)是您实例化了BaseRepostiory而不是customRepo对象。

Polymorphism invokes the most derived function of the type that was actually created , so creating a customRepo object will invoke customRepo.C, and creating a BaseRepository will invoke BaseRepository.C. 多态会调用实际创建的类型中最派生的函数,因此创建customRepo对象将调用customRepo.C,而创建BaseRepository将调用BaseRepository.C。

To expound further, classes do not magically know about their derivations, nor do they call derived methods. 更进一步地讲,类并不神奇地知道它们的派生,也不调用派生的方法。 This makes sense, because if you had multiple derivations, which method would you call? 这是有道理的,因为如果您有多个派生,您将调用哪种方法? The following line will work as you expect (calling the derived class): 以下行将按您期望的方式工作(调用派生类):

BaseRepository custom = new customRepo();
custom.A();

This one will not: 这将不会:

BaseRepository base = new BaseRepostiory();
base.A();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM