使用 delphi 将二维数组导入 class

Importing a 2d array into a class with delphi

我正在尝试在 create 方法中创建一个带有二维数组 (arrscore) 的 class,我对此进行了一些研究,这是我目前为止的研究。

constructor create(spriority, sSelOne, sSeltwo, sSelthree: string; arrcountry: array of string; arrscore: array of real);

这是我的 classes 变量声明

type
  tMap = class
  private
    // variables
    priority, selone, seltwo, selthree: string;
    country: array of string;
    score: array of real;

这是我的创建代码

 begin
  priority := spriority;
  selone := sSelOne;
  seltwo := sSeltwo;
  selthree := sSelthree;
  country := arrcountry;
  score := arrscore;
end;

这不起作用,因为它是动态数组和实数数组的不兼容类型。 提前致谢。

是的,这很烦人。

如果您使用 open array parameters,传统上您必须以繁琐的手动方式复制数组:

var
  country: array of string; // dynamic array
  score: array of Real; // dynamic array

// open array parameters
constructor Create(...; const arrcountry: array of string; const arrscore: array of Real);
var
  i: Integer;
begin
  SetLength(country, Length(arrcountry));
  for i := 0 to High(arrcountry) do
    country[i] := arrcountry[i];
  // similarly for score/arrscore
end;

但是,作为 David Heffernan points out, recent Delphi versions also provide the TArray.Copy<T> 程序:

SetLength(country, Length(arrcountry));
TArray.Copy<string>(arrcountry, country, Length(arrcountry));
SetLength(score, Length(arrscore));
TArray.Copy<Real>(arrscore, score, Length(arrscore));

但是如果你改用dynamic array参数,你可以做到

var
  country: TArray<string>; // dynamic array
  score: TArray<Real>; // dynamic array

// dynamic array parameters
constructor Create(...; arrcountry: TArray<string>; arrscore: TArray<Real>);
begin
  country := arrcountry;
  score := arrscore;
end;

请注意,数组不会被复制,因此您对 country 所做的任何更改都会影响调用者的数组(因为它是同一个数组)。

如果要复制,请执行

country := Copy(arrcountry);
score := Copy(arrscore);