delphi - 将 TPoint 数组存储在 TObjectList 中

标签 delphi

我定义了一个对象列表来存储多个多边形,如 TFPolygon = 此 TObjectList 内的 TPoint 数组;但使用我的对象列表的添加功能时,我收到访问冲突错误 :

type
  TFPolygon = array of TPoint;
  TFPolygonList = class(TObjectList)
  private
    procedure SetPolygon(Index: Integer; Value: TFPolygon);
    function GetPolygon(Index: Integer): TFPolygon;
  public
    procedure Add(p: TFPolygon);
    property Items[index: Integer]: TFPolygon read GetPolygon write SetPolygon; default;
  end;

implementation

procedure TFPolygonList.SetPolygon(Index: Integer; Value: TFPolygon);
begin
  inherited Items[Index] := Pointer(Value);
end;

function TFPolygonList.GetPolygon(Index: Integer): TFPolygon;
begin
  Result := TFPolygon(inherited Items[Index]);
end;

procedure TFPolygonList.Add(p: TFPolygon);
begin
  inherited Add(Pointer(p));
end;

我无法理解此代码示例中的错误?我可以只将类存储在 TObjectList 中吗?或者我存储 TPoint 数组的方法也有效吗?

最佳答案

您的方法无效。动态数组是托管类型。它们的生命周期由编译器管理。为了使其发挥作用,您一定不能放弃它们是托管类型的事实,这正是您所做的。

您将动态数组转换为 Pointer 。此时,您已经对动态数组进行了新的引用,但编译器不知道它,因为 Pointer不是托管类型。

您有几个选项可以解决您的问题。

  1. 如果您使用的是现代 Delphi,请停止使用 TObjectList 。相反,请使用 Generics.Collections 中的通用类型安全容器。 。在你的情况下TList<TFPolygon>就是你所需要的。因为这是编译时类型安全的,所以托管类型的所有生命周期都会得到照顾。
  2. 如果您使用的是较旧的 Delphi,那么您可以将动态数组包装在类中。然后将这些类的实例添加到您的 TObjectList 中。确保您的列表配置为拥有其对象。您完全有可能纯粹在 TFPolygonList 的实现中进行这种包装。这将很好地封装事物。

关于delphi - 将 TPoint 数组存储在 TObjectList 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15661678/

相关文章:

delphi - 处理添加到 TStringList 的对象

Delphi 和 IdFtp - 如何将所有文件上传到目录中

delphi - 检查 Advantage 数据库连接的运行状况

delphi - 如何在单击按钮时动态地将组件添加到 TScrollBox 中?

delphi - 通用字典类是否有通过索引获取键的方法?

delphi - 将 VirtualStringTree 导出到 excel、csv?

delphi - 在 Windows 7 64 位上运行的 Delphi 6 中找不到代码资源管理器窗口。如何取回?

delphi - 确定要使用的字符集

带登录/注销的 Delphi 应用程序 - 如何实现?

Delphi 多个异常处理 block 的异常处理问题