变体记录的 Rtti

发布于 2024-08-31 13:54:43 字数 319 浏览 12 评论 0原文

我尝试用 Delphi 2010 编写一种对象/记录序列化器,想知道是否有办法检测记录是否是变体记录。例如,Types.pas 中定义的 TRect 记录:

TRect = record
case Integer of
  0: (Left, Top, Right, Bottom: Longint);
  1: (TopLeft, BottomRight: TPoint);
end; 

由于我的序列化程序应该在我的数据结构上递归工作,因此它将下降到 TPoint 记录并在我的序列化文件中生成冗余信息。有没有办法通过获取记录中的详细信息来避免这种情况?

I try to write a kind of object/record serializer with Delphi 2010 and wonder if there is a way to detect, if a record is a variant record. E.g. the TRect record as defined in Types.pas:

TRect = record
case Integer of
  0: (Left, Top, Right, Bottom: Longint);
  1: (TopLeft, BottomRight: TPoint);
end; 

As my serializer should work recursively on my data structures, it will descent on the TPoint records and generate redundant information in my serialized file. Is there a way to avoid this, by getting detailed information on the record?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

年华零落成诗 2024-09-07 13:54:43

一种解决方案可能如下:

procedure SerializeRecord (RttiRecord : TRttiRecord)

var
  AField : TRttiField;
  Offset : Integer;

begin
Offset := 0;
for AField in RttiRecord.Fields do
  begin
  if AField.Offset < Offset then Exit;
  Offset := AField.Offset; //store last offset
  SerializeField (AField);
  end;
end;

但该解决方案并不是适合所有情况的正确解决方案。它仅适用于序列化,如果不同的变体包含相同的信息和相同的类型。如果您有类似以下内容(来自 wikipedia.org):

type   
  TVarRec = packed record
  case Byte of
    0: (FByte: Byte;
        FDouble: Double);
    1: (FStr: ShortString);
  end;

您会序列化

FByte=6
FDouble=1.81630607010916E-0310

还是序列化会更好 是

FStr=Hello!

的,当然,这对于计算机来说也是相同的,但对于应该可读甚至可编辑的文件来说则不同对于人类来说。

所以我认为,解决问题的唯一方法是使用属性来定义应该使用哪个变体进行序列化。

One solution could be as follows:

procedure SerializeRecord (RttiRecord : TRttiRecord)

var
  AField : TRttiField;
  Offset : Integer;

begin
Offset := 0;
for AField in RttiRecord.Fields do
  begin
  if AField.Offset < Offset then Exit;
  Offset := AField.Offset; //store last offset
  SerializeField (AField);
  end;
end;

But this solution is not a proper solution for all cases. It only works for serialization, if the different variants contain the same information and the same types. If you have something like the following (from wikipedia.org):

type   
  TVarRec = packed record
  case Byte of
    0: (FByte: Byte;
        FDouble: Double);
    1: (FStr: ShortString);
  end;

Would you serialize

FByte=6
FDouble=1.81630607010916E-0310

or would it be better to serialize

FStr=Hello!

Yes, for sure, this would also be the same for a computer but not for a file which should be readable or even editable for humans.

So I think, the only way to solve the problem is using an Attribute, to define, which variant should be used for serialization.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文