程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在 Delphi 中处理多个相似的变量/对象大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决在 Delphi 中处理多个相似的变量/对象?

开发过程中遇到在 Delphi 中处理多个相似的变量/对象的问题如何解决?下面主要结合日常开发的经验,给出你关于在 Delphi 中处理多个相似的变量/对象的解决方法建议,希望对你解决在 Delphi 中处理多个相似的变量/对象有所启发或帮助;

我正在编写一个使用多种形状的程序,我需要创建一个程序将它们全部变成白色。有问题的形状被命名为 @H_801_3@Sectorborder1 到 @H_801_3@Sectorborder20。

有没有办法像这样或类似地处理形状?

Sectorborder[X].brush.color := ClWhite;
Inc(X);

...其中 X 是数字(显然),而不必这样做:

Sectorborder1.brush.color := ClWhite;
Sectorborder2.brush.color := ClWhite;
...
Sectorborder20.brush.color := ClWhite;

所以基本上能够通过变量区分名称。这是我能想到的唯一描述方式。 (抱歉,有人也可以提供更好的描述吗?)任何建议都将不胜感激。

解决方法

使用数组

private
  SectorBorders: arraY[1..20] of TShape;

procedure TMyForm.FormCreate(Sender: TObject):
begin
  SectorBorders[1] := SectorBorder1;
  ..
  SectorBorders[20] := SectorBorder20;
end;

procedure TMyForm.SetAllToWhite;
var
  X: Integer;
begin
  for X := Low(SectorBorders) to High(SectorBorders) do
    SectorBorders[X].brush.Color := clWhite;
end;
,

作为数组的替代,您可以使用列表。如果您使用 System.Generics.Containers 中的 TList,您可以轻松地传递列表的所有元素。

你像这样使用它:

interface

uses  System.Generics.Collections;   // you need this to get the TList,you also need your other refereces of course

  ...

  protected
    pShapes:  TList<TShape>;

  procedure TMyForm.FormCreate(Sender: TObject):
  var
    nLoop: Integer;
  begin
    Self.pShapes:=TList<TShape>.Create;
    nLoop:=0;
    while(nLoop<Self.ComponentCount) do
    begin
      if(Self.Components[nLoop] is TShapE) then
        pList.Add(TShape(Self.Components[nLoop]));
      Inc(nLoop);
    end;
  end;

  procedure TMyForm.SetAllToWhite;
  var
    pShape:  TShape;
  begin
    for pShape in Self.pShapes do 
      pShape.brush.Color := clWhite;
  end;

选择使用数组还是 TList 部分取决于偏好,但也取决于您可能想对 TShapes 集合做什么以及它们在对象中的管理方式。

,

您可以使用表单的 FindComponent 方法。

shape:= FindComponent('SectorBorder' + IntToStr(i)) as TShape;
if shape <> nil then 
   pShape.brush.Color := clWhite;

http://docwiki.embarcadero.com/CodeExamples/Sydney/en/FindComponent_(Delphi)

大佬总结

以上是大佬教程为你收集整理的在 Delphi 中处理多个相似的变量/对象全部内容,希望文章能够帮你解决在 Delphi 中处理多个相似的变量/对象所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。