![](/img/trans.png)
[英]Force calling the derived class implementation within a generic function in C#?
[英]Calling a Derived class ovverridden function in c#
我有一个用作父类的类,它具有c()函数,我想在派生类中重写它,但是调用了基类c函数。 这是我班的伪代码。可能是这个关键字给了它整体一个不同的含义
public Class BaseRepository
{
public A()
{
this.c();
}
public B()
{
this.c();
}
protected virtual c()
{
enter code here
}
}
当我上这堂课时
class customRepo:BaseRepository
{
protected override c()
{
...does something
}
}
我的自定义回购函数未使用自定义回购类中的c()
,但正在使用基本回购类函数。 谁能告诉我为什么会这样吗?
发生这种情况的最可能的原因(也是我唯一能想到的)是您实例化了BaseRepostiory
而不是customRepo
对象。
多态会调用实际创建的类型中最派生的函数,因此创建customRepo
对象将调用customRepo.C,而创建BaseRepository
将调用BaseRepository.C。
更进一步地讲,类并不神奇地知道它们的派生,也不调用派生的方法。 这是有道理的,因为如果您有多个派生,您将调用哪种方法? 以下行将按您期望的方式工作(调用派生类):
BaseRepository custom = new customRepo();
custom.A();
这将不会:
BaseRepository base = new BaseRepostiory();
base.A();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.