是否可以在单独的单元中使用表单属性?

时间:2019-01-21 20:01:33

标签: delphi delphi-units

我正在使用delphi创建游戏,并且想要将我的一些代码移到一个单独的单元中,但是该代码使用表单中的属性。这可能吗?

我正在使用VCL表单应用程序创建游戏,目前在表单单元中有我所有的游戏算法代码。这没有什么错,因为我的程序运行良好,除了看起来很凌乱,并且建议我将算法代码放在单独的单元中。我尝试将代码移到新的单元中,但是无论如何尝试都会出现语法错误。

这是我主要单元中的代码,其中Grid是表单中的TStringGrid,而GridSize是我尝试的第二个单元中的过程:

procedure TGame.NewGame;
begin
  Grid.Width:=GridSize(Grid.ColCount);
  Grid.Height:=GridSize(Grid.RowCount);
end;

这是第二个单位代码:

unit UGameGenerator;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, 
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Grids, Vcl.Menus, 
  Vcl.StdCtrls;

implementation

function GridSize(size: integer): integer;
begin
  result:=291+36*(size-8);
end;

end.

编辑:

这是第二单元的代码:

procedure ClearGrid;
var
  i,j: integer;
begin
  for i := 0 to Grid.ColCount-1 do
  begin
    for j := 0 to Grid.RowCount-1 do
    begin
      Grid.Cells[i,j]:='';
    end;
  end;
end;

1 个答案:

答案 0 :(得分:2)

编译器需要以某种方式找到GridSize的声明。为此,请遵循以下指南:

  1. 在主表单中,将UGameGenerator添加到使用列表:

    unit MainForm;
    
    interface
    
    uses
      ...,UGameGenerator; // Add here or in the implementation section
    
    ...
    implementation
    
    ...
    
    end.
    
  2. 在您的UGameGenerator单元中,在界面中公开在其他程序部分中使用的所有类型/功能/过程:

    unit UGameGenerator;  
    
    interface
    
    uses
      ...,...;
    
    function GridSize(size: integer): integer;  
    
    implementation
    
    function GridSize(size: integer): integer;
    begin
      result:=291+36*(size-8);
    end;        
    
    end.
    

设计单独单元时的提示,请避免直接使用其他单元中的变量。而是在过程/函数调用中将它们作为参数传递。

否则,您可能会在循环引用方面遇到很多麻烦。

在更新的问题中,声明procedure ClearGrid( aGrid : TStringGrid);并将网格作为参数传递。