问题描述
pos := IntToStr(comp1[5]);
with TLabel (FindComponent('Labelc'+pos)) do Caption:=comp1n;
with TLabel (FindComponent('Labelc'+pos+'w')) do Caption:=IntToStr(comp1[1]);
with TLabel (FindComponent('Labelc'+pos+'l')) do Caption:=IntToStr(comp1[2]);
with TLabel (FindComponent('Labelc'+pos+'d')) do Caption:=IntToStr(comp1[3]);
with TLabel (FindComponent('Labelc'+pos+'s')) do Caption:=IntToStr(comp1[4]);
pos := IntToStr(comp2[5]);
with TLabel (FindComponent('Labelc'+pos)) do Caption:=comp2n;
with TLabel (FindComponent('Labelc'+pos+'w')) do Caption:=IntToStr(comp2[1]);
with TLabel (FindComponent('Labelc'+pos+'l')) do Caption:=IntToStr(comp2[2]);
with TLabel (FindComponent('Labelc'+pos+'d')) do Caption:=IntToStr(comp2[3]);
with TLabel (FindComponent('Labelc'+pos+'s')) do Caption:=IntToStr(comp2[4]);
pos := IntToStr(comp3[5]);
with TLabel (FindComponent('Labelc'+pos)) do Caption:=comp3n;
with TLabel (FindComponent('Labelc'+pos+'w')) do Caption:=IntToStr(comp3[1]);
with TLabel (FindComponent('Labelc'+pos+'l')) do Caption:=IntToStr(comp3[2]);
with TLabel (FindComponent('Labelc'+pos+'d')) do Caption:=IntToStr(comp3[3]);
with TLabel (FindComponent('Labelc'+pos+'s')) do Caption:=IntToStr(comp3[4]);
...
,依此类推,直到第十。 我一直在寻找类似FindComponent函数的东西,但要寻找变量,因此我可以将一段代码放入for循环中,但是似乎在pascal中,您无法将字符串连接成变量名。我所需要做的就是以某种方式动态地更改变量名,因此无需更改代码十次,唯一的改变就是comp1,comp2,comp3,... comp1,n,comp2n,comp3n等。 >
有什么建议吗?我真的很感激! (对不起,英语不好)
解决方法
未经测试的错误处理非常可怕,但至少与原始版本相同。
aggregate_data
如果pos始终是数组的第5个值,则
const letters : array [1..4] of char =('w','l','d','s');
Procedure TForm2.AssignLabel(pos:integer;const compxn:string;othercomp:array of integer);
Var i : integer;
poss : string;
Begin
poss:=inttostr(pos);
TLabel(FindComponent('Labelc'+poss)).caption:=compxn;
For i:=1 to 4 do
TLabel(FindComponent('Labelc'+poss+letters[i])).Caption:=IntToStr(othercomp[i-1]);
// othercomp i-1 because open array is always 0 based.
end;
// and then the calling reduces to
assignlabels(comp1[5],comp1n,comp1);
assignlabels(comp2[5],comp2n,comp2);
assignlabels(comp3[5],comp3n,comp3);