在delphi中将匿名类型数组传递给函数

问题描述 投票:0回答:1

我需要在delphi中创建过程,它将匿名类型的数组转换为指定类型的数组。我想要完成的事情:

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

这实际上是玩家可以定义自己的脚本的游戏程序。此脚本在运行时调用,因此上面的结构是唯一一个实际工作的脚本。

我想做的是将2个参数传递给这个函数:

  1. 用户定义类型的数组(我在游戏中不知道)
  2. 由string传递的此数组的类型

然后过程应该将传递的数组转换为此特定类型。我读到了TList,但我不能声明静态类型。

在.NET中,我能够传递动态(甚至是对象)数组并使用linq将其强制转换为目标类型,或者只是遍历动态列表。

这样的东西在delphi中实际上是可行的吗?任何帮助将不胜感激。

arrays list delphi
1个回答
-2
投票

德尔福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.
© www.soinside.com 2019 - 2024. All rights reserved.