将TPoint的数组存储在TObjectList中 [英] store array of TPoint inside TObjectList

查看:48
本文介绍了将TPoint的数组存储在TObjectList中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个对象列表,将多个多边形存储为TFPolygon = TObjectList中的TPoint数组;但是使用我的对象列表的添加功能时,出现访问冲突错误:

I defined a Objectlist to store several Polygons as TFPolygon = array of TPoint inside this TObjectList; but with the add function of my objectlist I get an Access violation error :

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内还是存储TPoints数组的方法也有效?

I can not understand the error inside this code sample ? Can I only store classes inside a TObjectList or is my approach to store arrays of TPoints also valid ?

推荐答案

您的方法无效.动态数组是托管类型.它们的生存期由编译器管理.为此,您一定不要抛弃它们是托管类型的事实,而这正是您所做的.

Your approach is not valid. Dynamic arrays are managed types. Their lifetimes are managed by the compiler. For that to work you must not cast away the fact that they are managed types, which is exactly what you did.

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

You cast the dynamic array to Pointer. At that point you have taken a new reference to the dynamic array, but the compiler is not aware of it because a Pointer is not a managed type.

您有一些选择可以解决您的问题.

You've got a few options to solve your problem.

  1. 如果您使用的是现代Delphi,请停止使用 TObjectList .而是在 Generics.Collections 中使用通用类型的安全容器.在您的情况下,您需要 TList< TFPolygon> .因为这是安全的编译时类型,所以托管类型的所有生命周期都得到了照顾.
  2. 如果您使用的是较旧的Delphi,则可以将动态数组包装在一个类中.然后将这些类的实例添加到您的 TObjectList 中.确保您的列表配置为拥有其对象.您完全有可能完全在 TFPolygonList 的实现中进行包装,这样可以很好地封装内容.
  1. If you are on a modern Delphi then stop using TObjectList. Instead use the generic type safe containers in Generics.Collections. In your case TList<TFPolygon> is what you need. Because this is compile time type safe, all the lifetime of the managed types is taken care of.
  2. If you are on an older Delp then you can wrap your dynamic array inside a class. Then add instances of those classes to your TObjectList. Make sure that your list is configured to own its objects. It's perfectly possible for you to do that wrapping purely in the implementation of TFPolygonList which will encapsulate things well.

这篇关于将TPoint的数组存储在TObjectList中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆