集合类型表示一组值,该组值由集合所依据的有序类型定义。定义集合的常用有序类型不多,一般为枚举类型或子界类型。如果子界类型取值为 1..3,那么基于它的集合类型值可以是 1、或 2、或 3、或 1 和 2、或 1 和 3、或 2 和 3、或取所有 3 个数、或一个数也没有。
//定义 type Uppercase = 'A'..'Z'; Letters = set of Uppercase; //基于子界定义 TBorderIcon = (biSystemMenu, biMinimize, biMaximize, biHelp); TBorderIcons = set of TBorderIcon; //基于枚举定义 -------------------------------------------------------------------------------- //应用 type Uppercase = 'A'..'Z'; Letters = set of Uppercase; //基于子界定义 var L1, L2, L3: Letters; begin L1 := ['A', 'B', 'C']; L2 := ['K']; L3 := []; if 'A' in L1 then ShowMessage('true'); //true if L2=['K'] then ShowMessage('true'); //true if L3=[] then ShowMessage('true'); //true end; -------------------------------------------------------------------------------- //判断是否属于集合 type TSet = set of (A,B,C); var set1: TSet; begin set1 := [A,B]; if A in set1 then ShowMessage('集合 set1 包含 A'); end; -------------------------------------------------------------------------------- //集合元素的增减 type TSet = set of (A,B,C); var set1: TSet; begin set1 := [A]; set1 := set1 + [B]; //增加一个元素 Include(set1,B); //增加一个元素 set1 := set1 - [B]; //排除一个元素 Exclude(set1,B); //排除一个元素 end; -------------------------------------------------------------------------------- //集合添加元素举例 type TCharSet = set of char; var character: 'a'..'z'; charSet: TCharSet; word: string; begin charSet := []; for character in [Low(character) .. High(character)] do begin if character in ['d', 'e', 'l', 'p', 'h', 'i'] then begin Include(charSet, character); end; end; for character in charSet do begin word := word + character; end; ShowMessage(word); //dehilp end; //交集 procedure TForm1.FormCreate(Sender: TObject); type TSet = set of (A,B,C,D,E,F,G); var set1,set2,set3: TSet; begin set1 := [A,B,C]; set2 := [C,D,E]; set3 := set1 * set2; {现在 set3 应该是 [C], 测试下} if set3 = [C] then ShowMessage('Ok'); end;