Check if an object inherits from a common class

I have a generic list class:

TMyObjectlist<T: TMyObject> = class(TObjectList<T>);

and list derived class:

TMyDerivedObjectList = class(TMyObjectList<TMyDerivedObject>);

I want to check if an instance of MyList TMyDerivedObjectList really inherits from TMyObjectList:

MyList.InheritsFrom(TMyObjectlist<TMyObject>)

returns false.

It turns out that MyList.Classparent is of type TMyObjectList<TMyDerivedObject>.

Does anyone know how to check InheritsFrom in this case?

+3
source share
4 answers

Just create an inheritance scheme for both list objects and you will clearly see why InheritsFrom is not working. At Generics.Collections, we have:

TEnumerable<T> = class abstract;
TList<T> = class(TEnumerable<T>);
TObjectList<T> = class(TList<T>);

In your example, we have:

TMyObject = class;
TMyDerivedObject = class(TMyObject);

So, we get these two inheritance trees:

TObject
|
TEnumerable<TMyDerivedObject>
|
TList<TMyDerivedObject>
|
TObjectList<TMyDerivedObject>

and then we have:

TObject
|
TEnumerable<TMyObject>
|
TList<TMyObject>
|
TObjectList<TMyObject>

, TObject!

+6

, , . , . , , , .

, , MyList , TMyObjectlist<TMyObject>. , . TMyIncompatibleObject, TMyObject. .

, Delphi. , Delphi , Generics .

+1

In Delphi, constructed types are not covariant with their type parameters. Given T, U, Vand U <= Vthen T<U> is not <= T<V>.

See Covariance and contravariance .

+1
source

TObjectList<t> does not exist in the compiled code of the instance that was created when specifying the type exists.

So, you cannot check if it is derived from an unsafe class.

0
source

Source: https://habr.com/ru/post/1751213/


All Articles