简体   繁体   中英

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. 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. 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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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