求一段代码的简化方式。。 ( 积分: 50 )

  • 主题发起人 主题发起人 Jason Law
  • 开始时间 开始时间
J

Jason Law

Unregistered / Unconfirmed
GUEST, unregistred user!
总觉得下面的代码写得很笨 ,有什么办法可以简单化吗?
var
MyIni:TIniFile ;
begin
MyIni :=TIniFile.Create('C:/setup.ini'));
try
MyIni.WriteString('BottonCaption','1',BitBtn1.Caption);
MyIni.WriteString('BottonCaption','2',BitBtn2.Caption);
MyIni.WriteString('BottonCaption','3',BitBtn3.Caption);
MyIni.WriteString('BottonCaption','4',BitBtn4.Caption);
MyIni.WriteString('BottonCaption','5',BitBtn5.Caption);
MyIni.WriteString('BottonCaption','6',BitBtn6.Caption);
MyIni.WriteString('BottonCaption','7',BitBtn7.Caption);
MyIni.WriteString('BottonCaption','8',BitBtn8.Caption);
MyIni.WriteString('BottonCaption','9',BitBtn9.Caption);
MyIni.WriteString('BottonCaption','10',BitBtn10.Caption);
MyIni.WriteString('BottonCaption','11',BitBtn11.Caption);
MyIni.WriteString('BottonCaption','12',BitBtn12.Caption);
MyIni.WriteString('BottonCaption','13',BitBtn13.Caption);
MyIni.WriteString('BottonCaption','14',BitBtn14.Caption);
MyIni.WriteString('BottonCaption','15',BitBtn15.Caption);
MyIni.WriteString('BottonCaption','16',BitBtn16.Caption);
MyIni.WriteString('BottonCaption','17',BitBtn17.Caption);
MyIni.WriteString('BottonCaption','18',BitBtn18.Caption);
MyIni.WriteString('BottonCaption','19',BitBtn19.Caption);
MyIni.WriteString('BottonCaption','20',BitBtn20.Caption);
finally
MyIni.Free;
end;
 
var
MyIni: TIniFile;
i: Integer;
str: string;
tempcon: TComponent;
begin
MyIni := TIniFile.Create('C:/setup.ini'));
try
for i := 1 to 20 do
begin
str := 'Unknown';
tempcon := FindComponent('BitBtn' + IntToStr(i));
if tempcon is TBitBtn then
str := (tempcon as TBitBtn).Caption;
MyIni.WriteString('BottonCaption', IntToStr(i), str);
end;
finally
MyIni.Free;
end;
 
var I, BtnNum:integer
tpName: String;

For i:=0 to self.ComponentCount-1 do
if self.Components is TBitBtn then
With TBitBtn(self.Components) do begin
tpName:=Name;
Delete(tpName,1,6);
try
BtnNum := StrToInt(tpName);
Except
BtnNum :=0;
end;
if (BtnNum > 0) and (BtnNum < 21) then //如果不连续,还可以用 BtnNum in [1,2,3,5,7,9,23]等集合操作
MyIni.WriteString('BottonCaption',tpName,Caption);
end;
大致思路就这样,代码没测试过,只接在这里写的。
 
这种情况用Tag就很简单了

var
I: Integer;
begin
with TIniFile.Create('C:/setup.ini') do
try
for I := 0 to ComponentCount - 1 do
if Components is TBitBtn then
WriteString('BottonCaption', IntToStr(Components.Tag), TBitBtn(Components).Caption);
finally
Free;
end;
end;
 
呵呵,学习。
看起来ANiDelphi的方法不错,有机会试一下。
 
后退
顶部