如何在Delphi中调用虚方法的当前层级(非多态)版本?
在Delphi中调用虚方法的当前层级(非多态)版本
类定义
Parent = class public procedure virtFunc(); virtual; procedure other(); end; Child = class(Parent) public procedure virtFunc(); override; end;
需求场景
通常调用Child实例的virtFunc时,会执行Child中的重写实现。但在Parent的other方法中,希望调用Parent自身的virtFunc实现,而非被Child重写的版本:
procedure Parent.other(); begin virtFunc(); // 此处希望执行Parent.virtFunc(),而非Child.virtFunc() end;
已尝试的无效方法
Parent(Self).virtFunc()(Self as Parent).virtFunc()
不考虑的替代方案
- 为方法重命名(如区分
childFunc和parentFunc) - 移除
virtual修饰符
解决方案
在Delphi中,要实现类似C++里Parent::virtFunc()的非多态调用,直接通过类名+方法名的方式显式调用,并传入Self参数即可:
procedure Parent.other(); begin Parent.virtFunc(Self); // 直接调用Parent类的virtFunc实现,绕过虚表 end;
这种写法会跳过虚方法的多态机制,无论当前Self实际指向Parent还是Child实例,都会执行Parent类中定义的virtFunc实现。
内容的提问来源于stack exchange,提问作者Adrian Maire
相关产品推荐
相关产品推荐

