Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my code not compile, but rather gets E2506 Method of parameterized type declared in interface section must not use local symbol

I am using Delphi XE.

The following unit fails to compile with this error:

[DCC Error] GTSJSONSerializer.pas(27): E2506 Method of parameterized type declared 
   in interface section must not use 
   local symbol 'TSuperRttiContext.AsJson<GTSJSONSerializer.TGTSJSONSerializer<T>.T>'

Why is that? Is there a workaround?

unit GTSJSONSerializer;

interface

type
   TGTSJSONSerializer<T> = class
     class function SerializeObjectToJSON(const aObject: T): string;
     class function DeserializeJSONToObject(const aJSON: string): T;
   end;

implementation

uses
        SuperObject
      ;

class function TGTSJSONSerializer<T>.SerializeObjectToJSON(const aObject: T): string;
var
  SRC: TSuperRttiContext;
begin
  SRC := TSuperRttiContext.Create;
  try
    Result := SRC.AsJson<T>(aObject).AsString;
  finally
    SRC.Free;
  end;
end;

class function TGTSJSONSerializer<T>.DeserializeJSONToObject(const aJSON: string): T;
var
  LocalSO: ISuperObject;
  SRC: TSuperRttiContext;
begin
  SRC := TSuperRttiContext.Create;
  try
    LocalSO :=  SO(aJSON);
    Result := SRC.AsType<T>(LocalSO);
  finally
    SRC.Free;
  end;
end;

end.
like image 748
Nick Hodges Avatar asked Dec 02 '11 21:12

Nick Hodges


2 Answers

From the XE2 DocWiki:

This happens when trying to assign a literal value to a generics data field.

program E2506;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type
  TRec<T> = record
  public
    class var x: Integer;
    class constructor Create;
  end;

class constructor TRec<T>.Create;
begin
  x := 4; // <-- e2506 Fix: overload the Create method to 
          // take one parameter x and assign it to the x field.
end;

begin
   Writeln('E2506 Method of parameterized type declared' +
           ' in interface section must not use local symbol');
end.

I can't tell which of the local variables it might be objecting to, though; you have one local in SerialObjectToJSON and two in DeserializeJSONToObject. I'm also not sure based on the linked fix exactly how that applies to the code you posted. Could it be related to TSuperRTTIContext?

like image 95
Ken White Avatar answered Nov 04 '22 11:11

Ken White


I can compile your unit with D2010, DXE and DXE2 against SuperObject revision 46.

like image 37
Uwe Schuster Avatar answered Nov 04 '22 11:11

Uwe Schuster