我有这些类和一个过程:

 TParent = class(TObject);
 TChild1 = class(TParent);
 TChild2 = class(TParent);

 Procedure DoSomething(obj:TParent);

我想做的是当objTParent而不是后代引发异常时。

我考虑过做这样的事情:
if obj.classname = TParent.classname then raise exception.create....

但似乎有点骇人听闻(TM)

更多:我想要的是能够传递具有共同属性/过程的对象。经过更多的思考,根本不需要TParent对象,我需要的是答案中显示的接口(interface)对象。

最佳答案

您可能会发现以下TObject类方法很有用:

  • ClassType-返回对象的类
  • ClassParent-给出类
  • 的父类
  • InheritsFrom-返回一个类是否从另一个类继承(即检查整个继承链)。它包括当前类。

  • 因此,您可以使用类似以下代码的代码来实现所需的功能(从TParent降到TDescendant而不是TDescendant?)(未经测试,目前没有Delphi):
    if obj.ClassType.InheritsFrom(TParent)
      and not obj.ClassType.InheritsFrom(TDescendant) then...
    

    或者,如果我误解了,而您只想查看对象是否是TParent,而不是根本没有任何后代,请尝试:
    if obj.ClassType = TParent then...
    

    Delphi通过metaclasses提供对类的访问,从而领先于时代,因此,您不仅可以检查类名,还可以访问实际的类对象。

    10-05 20:40
    查看更多