I have these classes and a procedure:
TParent = class(TObject);
TChild1 = class(TParent);
TChild2 = class(TParent);
Procedure DoSomething(obj:TParent);
What I would like to do is when obj
is a TParent
and not a descendant raise an exception.
I thought about doing something like this:
if obj.classname = TParent.classname then raise exception.create....
but it seems a bit hackish (TM)
More: What i intended is to able to pass objects that shared properties/procedures in common. After more thought, the TParent Object isn't really needed at all, what i needed was an interface object shown in my answer.
You'll probably find the following TObject
class methods useful:
So, you could achieve what you want (descends from TParent but not TDescendant?) with something like the following code (untested, don't have Delphi at this moment):
if obj.ClassType.InheritsFrom(TParent)
and not obj.ClassType.InheritsFrom(TDescendant) then...
Or, if I've misunderstood and you just want to see if an object is a TParent, and not any kind of descendant at all, try:
if obj.ClassType = TParent then...
Delphi was way ahead of its time by providing access to classes via metaclasses, so rather than just checking the class name you can access an actual class object.