Delphi中record的使用

1. 首先了解到record是可以限制field的范围的,而且定义枚举类型的。

type TDateRec = record

Year: Integer;

Month: (Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec);

Day: 1..31;

end;

2. 可以在不定义结构体的情况下,直接在变量声明时使用。

var S: record

Name: string;

Age: Integer;

end;

3. 下面是变体部分,这是Delphi中变体在结构中的标准定义

type recordTypeName = record

fieldList1: type1;

...

fieldListn: typen;

case tag: ordinalType of

constantList1: (variant1);

...

constantListn: (variantn);

end;

Ø Tag可以省略

Ø constantList的类型和ordinalType的类型一致

Ø fieldList的类型不能是long strings, dynamic arrays, variants,也不能是包含这些的结 构体,但可以是指向这些类型的指针

Ø TagconstantLists 在编译器处理这些字段时没有用,只是为程序员理解时提供方便 (原文:The optional tag and the constantLists play no role in the way the compiler manages the fields; they are there only for the convenience of the programmer.

Ø 使用变体结构体的两个原因:一个是需要不同的数据,但是又不会同时需要所有的字段。

type TEmployee = record

FirstName, LastName: string[40];

BirthDate: TDate;

case Salaried: Boolean of

True: (AnnualSalary: Currency);

False: (HourlyWage: Currency);

end;

Ø 另一个原因是可以把同样的数据就像是不同的类型的数据。比如,你有一个64位的实数做为第一个字段,你就可以把它的高32位作为整数返回。这是Delphi帮助里说的。不太好看出来,而且Real到Interger的转换我也很少用。弄个Word到Byte的结构到时很常用。

Type

RConversion = record

Case Boolean of

True   : (aWord: Word;);

False   : (abyte bbyte : Byte;);

end;

这里附加一句观点,我和周围的同事认为这样的结构体会造成代码的易读性降低,一般在自己的代码中不建议使用,当然为兼容Windows的一些结构除外,他本来就是union当然用这样的直接套用就可以了。

结构体的基本应用就是这样的。还有一些特殊的应用,比如“class-like”的结构体,和file of record。

Class-like的结构体我不知道什么时候使用,既然需要Create,用类不就得了。下面有篇文章对原理有一些阐述http://blog.csdn.net/maozefa/archive/2007/08/27/1760612.aspx。

File of record,个人比较喜欢,特别是在记录某种数据的时候,经常是把一个结构体整个写入到文件里,既实现了一定程度的加密,又简单方便,读出来也可以直接放进结构体里。这里就不详细描述了。

你给了我眼睛,却不给我光明。
原文地址:https://www.cnblogs.com/wwb0111/p/3098941.html