views:

60

answers:

1

How do I convert the TypeIdenitifier to a class type? I need to use implicit convertion.

type
  TMyChildArray<T>=class(TMyArray<T>)
    private
      FData:Array of T;
      procedure AddEnd();
  end;

  TTypeIdenitifierParentClass=class(TAnotherParentClass)
    protected
      TestField:Cardinal;
  end;


  procedure TMyChildArray<T>.AddEnd();
  var elem:T;
  begin
    for elem in Fdata do
      TTypeIdenitifierParentClass(elem).TestField:=0;
  end;

I get "Invalid typecast" on the implicit convertion "TTypeIdenitifierParentClass(elem).TestField:=0;".

The principle I want to use is that the TypeIdenitifier will represent a class that descends from TTypeIdenitifierParentClass.There are many class types,but all of them descend that class.

How do I do this?

+2  A: 

The reason delphi is complaining about the cast is because the compiler has no way of knowing if T can be type casted to "TTypeIdenitifierParentClass". You need to limit T to classes descending from "TTypeIdenitifierParentClass"

Try the following

type
  TTypeIdenitifierParentClass=class(TAnotherParentClass)
    protected
      TestField:Cardinal;
  end;

  TMyChildArray<T: TTypeIdenitifierParentClass>=class(TMyArray<T>)
    private
      FData:Array of T;
      procedure AddEnd();
  end;

  procedure TMyChildArray<T>.AddEnd();
  var elem:T;
  begin
    for elem in Fdata do
      elem.TestField:=0;
  end;
Fritz Deelman
Exactly what I did! :)
John