我如何确定抽象方法是否已实现?
我正在使用一个非常大的delphi第三方库,没有源代码,这个库有几个带有抽象方法的类。我需要确定子孙类在运行时何时实现抽象方法,以避免出现 EAbstractError: Abstract Error 并向用户显示自定义消息或改用另一个类。
例如,在这段代码中,我想在运行时检查 MyAbstractMethod
是否已实现。
type
TMyBaseClass = class
public
procedure MyAbstractMethod; virtual; abstract;
end;
TDescendantBase = class(TMyBaseClass)
public
end;
TChild = class(TDescendantBase)
public
procedure MyAbstractMethod; override;
end;
TChild2 = class(TDescendantBase)
end;
如何在运行时确定抽象方法是否在后代类中实现?
I'm using a very large delphi third party library without source code, this library has several classes with abstract methods. I need to determine when an abtract method is implemented by a Descendant class in runtime to avoid the EAbstractError: Abstract Error
and shows a custom message to the user or use another class instead.
for example in this code I want to check in runtime if the MyAbstractMethod
is implemented.
type
TMyBaseClass = class
public
procedure MyAbstractMethod; virtual; abstract;
end;
TDescendantBase = class(TMyBaseClass)
public
end;
TChild = class(TDescendantBase)
public
procedure MyAbstractMethod; override;
end;
TChild2 = class(TDescendantBase)
end;
How I can determine if an abstract method is implemented in a Descendant class in runtime?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 Rtti,
GetDeclaredMethods
函数获取以下列表在反射(当前)类型中声明的所有方法。因此,您可以检查该方法是否存在于该函数返回的列表中。或者您可以比较
Parent.Name
属性TRttiMethod 并检查是否与当前类名称匹配。you can use the Rtti, the
GetDeclaredMethods
function get a list of all the methods that are declared in the reflected (current) type. So you can check if the method is present in the list returned by this function.or you can compare the
Parent.Name
property of the TRttiMethod and check if match with the current class name.查看 VCL 源代码(在
Classes.pas
中)中 32 位版本的TStream.Seek()
方法的实现。它执行检查以确保在调用Seek()
的 64 位版本之前已被覆盖。它不涉及TRttiContext
查找来执行此操作,只是通过其父/子 VTable 条目进行简单循环,类似于 Zoë 的答案所示。Look at the implementation of the 32-bit version of the
TStream.Seek()
method in the VCL source code (inClasses.pas
). It performs a check to make sure the 64-bit version ofSeek()
has been overridden before calling it. It doesn't involveTRttiContext
lookups to do that, just a simple loop through its Parent/Child VTable entries, similar to how Zoë's answer shows.