我需要创建一个包含记录对象数组的类,但尝试使用 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/