user1573626
user1573626

Reputation: 31

Error passing a generic type from a class to another

I am using Delphi 2010

I get the error: E2506 Method of parameterized type declared in interface section must not use local symbol.

Is there a way to accomplish this task?

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, Rtti;

type

  MyFormType<T: TForm> = class
    class procedure SpecialOpen(var FormVar: T; Params: array of TValue);
  end;

  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    procedure ShowForm<T1: TForm>(var aForm: T1);
  end;

var
  Form1: TForm1;

implementation

uses Unit2;

{$R *.dfm}

procedure TForm1.ShowForm<T1>(var aForm: T1);
begin
  if aForm = nil then
    MyFormType<T1>.SpecialOpen(aForm, [Self])    // <-- Error
  else
    aForm.Show;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  ShowForm<TForm2>(Form2)
end;

{ MyFormType<T> }

class procedure MyFormType<T>.SpecialOpen(var FormVar: T; Params: array of TValue);
var lRttiContext: TRttiContext;
begin
  FormVar := lRttiContext.GetType(TClass(T)).GetMethod('Create').Invoke(TClass(T), Params).AsType<T>;
  FormVar.Show;
end;

end.

Tanks and sorry for my english.

Upvotes: 0

Views: 339

Answers (1)

David Heffernan
David Heffernan

Reputation: 612954

This is one of a great many generics bugs in Delphi 2010. Your code compiles in XE2. Your options are to look for a workaround that works in 2010, or to upgrade. Delphi XE and XE2 do include a great many fixes for generics compiler bugs and so if you are serious about making use of generics, Delphi 2010 is not a great choice.

Upvotes: 2

Related Questions