0
votes

I need to create procedure in delphi which will cast array of anonymous type to array of specified type. What I'am trying to accomplish:

procedure Foo (myArray: array of AnonymousType; typeName: string)
begin
//do smth on this array
end;

This is actually a procedure for a game where player can define his own script. This script is called at runtime so above structure is the only one which will actually work.

What I'am trying to do is pass 2 parameters into this function:

  1. array of user defined type (which I don't know in game)
  2. type of this array passed by string

And then procedure should convert passed array into this specific type. I read about TList, but I cannot declare static type.

In .NET I'am able to pass array of dynamic (or even object) and cast it to destination type using linq or simply iterate through dynamic list.

Is something like that actually possible in delphi? Any help will be appreciated.

1
There is no such thing as anonymous types in Delphi. If you are trying to let users define their own values, you need something like Variant, for instance. Or instances of type-specific class wrappers derived from TObject. What you are describing makes no sense in compiled languages like Delphi, only in scripted languages like Javascript/VBScript, Python, etc. In .NET, dynamic is just a placeholder for any object that derives from System.Dynamic.DynamicObject - Remy Lebeau
I would use array of const. - Victoria

1 Answers

-2
votes

Delphi DX10

uses
    Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
    Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
    System.Generics.Collections, System.Generics.Defaults, System.TypInfo;

type
    TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    private
        { Private declarations }
    public
        { Public declarations }
        function Foo<T>(AItem: T): String;
    end;

type
    TA1 = record
        X1, X2: Integer;
    end;

    TA2 = record
        W1, W2: String;
    end;

    TA3 = record
        Z1, Z2: real;
    end;

var
    Form1: TForm1;
    A1: TA1;
    A2: TA2;
    A3: TA3;

implementation

{$R *.dfm}

function TForm1.Foo<T>(AItem: T): String;
var
    LTypeInfo: PTypeInfo;
    GUID: TGUID;
begin
    { Get type info }
    LTypeInfo := TypeInfo(T);

    { Now you know name of type }
    Result := LTypeInfo.Name;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
    Foo<TA1>(A1);
    Foo<TA2>(A2);
    Foo<TA3>(A3);
end;

end.