S
S
SergioBarbery2014-10-01 13:10:13
Delphi
SergioBarbery, 2014-10-01 13:10:13

How to organize type inheritance when using generics in Delphi XE4-XE7?

We have 2 base classes:

TData = class; // Данные
TDataList<T: TData> = class(TObjectList<T>);  // Список
we also have several successors:
TData2 = class(TData);
TDataList2 = class(TDataList<TData2>);
TData3 = class(TData);
TDataList3 = class(TDataList<TData3>);
// ... и т.д.
Each list is a descendant of TDataList with its own data type inherited from TData.
It is required to be able to all these types TDataList2, TDataList3, etc. lead to a single parent type, to work at the level of TDataList lists and TData elements.
Tried this code:
procedure Test;
var
  DataListCommon: TDataList<TData>;
  DL2: TDataList2;
begin
  DL2 := TDataList2.Create;  // это можно опустить, на компилятор это не влияет
  DataListCommon := DL2;  // <-- [dcc32 Error] Unit1.pas(44): E2010 Incompatible types: 'Unit1.TDataList<Unit1.TData>' and 'TDataList2'
  DataListCommon := DL2 as TDataList<TData>; // Та-же ошибка  
  DataListCommon := TDataList<TData>(DL2);   // Компилируется и работает (по крайней мере ошибок замечено не было)
end;

How legitimate is it to use the compiled version of type casting in this case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
RomanYankovsky, 2014-10-22
@SergioBarbery

Here is an article about this delphisorcery.blogspot.de/2014/10/generics-and-var...
In short, you can't do this in Delphi. The method that you found is not very beautiful, but it works in practice. Works until you start adding elements of the wrong type to the list.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question