Delphi:如何在公共函数中使用ComponentCount?

Art*_*dio -2 delphi components class

我在下面有这个函数使用ComponetCount,当我在另一个Form中使用这个函数时,它在Form1中,在Form1中使用Form2,它带来了Form1而不是Form2的Componetes数量,我该如何解决这个问题问题?遵循功能:

function Form1.getgridId(KeyField: String): string;
var
  i: Integer;
  id: string;

begin

  for i := 0 to ComponentCount -1 do
  begin
    if Components[i] is TCustomDBGrid then
    id:= TCustomDBGrid(Components[i]).DataSource.DataSet.FieldByName(KeyField).AsString;
  end;
  Result := id;

end;
Run Code Online (Sandbox Code Playgroud)

ANS(在我的具体案例中) - 在所有人的帮助下:

function getgridId(KeyField: String): string;
var
  i: Integer;
  id: string;
begin
  for i := 0 to Screen.ActiveForm.ComponentCount -1 do
  begin
    if Screen.ActiveForm.Components[i] is TCustomDBGrid then
      id := TCustomDBGrid(Screen.ActiveForm.Components[i]).DataSource.DataSet.FieldByName(KeyField).AsString;
  end;
  Result := id;

end; 
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 6

您要求的是要求向函数添加参数以了解要迭代的Form:

function getgridId(Form: TForm; KeyField: String): string;
var
  i: Integer;
  id: string;
begin
  for i := 0 to Form.ComponentCount -1 do
  begin
    if Form.Components[i] is TCustomDBGrid then
      id := TCustomDBGrid(Form.Components[i]).DataSource.DataSet.FieldByName(KeyField).AsString;
  end;
  Result := id;
end;
Run Code Online (Sandbox Code Playgroud)

然后,当每个Form需要调用该函数时,它可以将它的Self指针作为第一个参数传递.

  • @Artur_Indio:`ComponentCount` /`Components []`*do*识别它们被调用的形式.你使你的函数成为`Form1`类的成员,你使用函数的'Self`参数访问`ComponentCount` /`Components []`,所以你总是使用`Form1`对象指针调用函数因此迭代通过`Form1`的组件,即使该函数实际上是从`Form2`调用的.要迭代`Form2`的组件,你必须使用`Form2`对象指针来访问`ComponentCount` /`Components []`,而你没有这样做. (2认同)