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,也不能是包含這些的結 構體,但可以是指向這些類型的指針
Ø Tag和constantLists 在編譯器處理這些字段時沒有用,只是爲程序員理解時提供方便 (原文: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,個人比較喜歡,特別是在記錄某種數據的時候,經常是把一個結構體整個寫入到文件裏,既實現了一定程度的加密,又簡單方便,讀出來也可以直接放進結構體裏。這裏就不詳細描述了。