在DELPHI没有FOR IN的语法时,我们要使用如下代码枚举数据集中的每个内容:
cds.First; while not cds.eof do begin ... cds.Next; end;
最少要四句,而且字数有些多.如果程序中大量使用这个,代码看起来总是不舒服.
在DELPHI XE,可以利用XE对 FOR IN 扩展,建立新的扩展,使用起来好象有点动态语言的味道:
unit faDataSetEx; interface uses DB,ADODB,Variants,SysUtils,StrUtils,Controls,System.Types,Classes,DBClient; type TFieldsEx = class helper for TFields private function GetFV (Index :String) :Variant; procedure SetFV (Index :String; const Value :Variant); public property FV[Index :String] :Variant read GetFV write SetFV; default; end; TDataSetEnumerator = class private FFirst :boolean; FDataSet :TDataSet; function GetCurrent :TFields; public constructor Create (dataset :TDataSet); function MoveNext :boolean; property Current :TFields read GetCurrent; end; TDataSetEx = class helper for TDataSet public function GetEnumerator :TDataSetEnumerator; end; implementation { TDataSetEx } function TDataSetEx.GetEnumerator :TDataSetEnumerator; begin Result := TDataSetEnumerator.Create (Self); end; { TDataSetEnumerator } constructor TDataSetEnumerator.Create (dataset :TDataSet); begin FDataSet := dataset; FFirst := True; end; function TDataSetEnumerator.GetCurrent :TFields; begin Result := FDataSet.Fields; end; function TDataSetEnumerator.MoveNext :boolean; begin if FFirst then begin FFirst := False; FDataSet.First; end else FDataSet.Next; Result := not FDataSet.eof; end; { TFieldsEx } function TFieldsEx.GetFV (Index :String) :Variant; begin Result := FieldByName (Index).Value; end; procedure TFieldsEx.SetFV (Index :String; const Value :Variant); begin FieldByName (Index).Value := Value; end; end.
有了上面单元的代码,我们可以这样枚举数据集的每个行:
var d :TFields; begin for d in cds1 do begin cds1.edit; d['a']:='abc'; cds1.post; end; end;
相当方便........