arrays - 带有动态数组的 DELPHI 类在 SetLength() 中有问题

标签 arrays delphi class dynamic

我需要创建一个包含记录对象数组,但尝试使用 SetLength 会引发访问冲突错误。

考虑以下带有水果的树对象示例。

type
TFruit = record
  color: string;
  weight: double;
end;

type
  TObjectTree = class

  Public
  Fruits: array of TFruit;

  constructor Create;
  procedure AddFruit;
end;

在实现中,当尝试调整 Fruit 对象数组的大小时或初始化为 nil 时会产生问题。

constructor TObjectTree.Create;
begin
    inherited Create;
    Fruits:=nil;              //Raises an error
end;


procedure TObjectTree.AddFruit(FruitColor: string; FruitWeight: integer);
begin
    SetLength(Fruits, Length(Fruits)+1);  //Raises an error (when I comment Fruits:=nil; in the constructor)

    Fruits[Length(Fruits)].color:=FruitColor;      
    Fruits[Length(Fruits)].weight:=FruitWeight;
end;

如何在类中使用动态数组?

最佳答案

替换

Fruits[Length(Fruits)].color:=FruitColor;      
Fruits[Length(Fruits)].weight:=FruitWeight;

Fruits[High(Fruits)].color:=FruitColor;
Fruits[High(Fruits)].weight:=FruitWeight;

然后就可以了。

关于arrays - 带有动态数组的 DELPHI 类在 SetLength() 中有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6833118/

相关文章:

c# - 从类继承并添加附加属性

c - 如何在C中将数组A的指针设置为指向数组B

arrays - 给定一个大小为 y 的数组,其中包含大小为 n 的数组,我如何使用 Ruby 返回所有逻辑组合?

c++ - 对象数组的选择排序

c++ - 在 ObjectPascal 中处理算术右移

c++ - 通过引用将数组从 Delphi 7 传递到 C++ Dll

php - 如何获取对象的非限定(短)类名?

javascript - 从 Node.js 中的 JSON 数组中读取一个值

java - 将 json 对象添加到 jsonarray android/Java

Delphi:调整表单大小时右对齐面板闪烁