Delphi 中没有与 C 静态变量直接等效的东西。
可写的类型常量(参见用户1092187的回答 https://stackoverflow.com/questions/8463604/true-c-static-local-variable-replacement#answer-8463815) 几乎是等价的。它具有相同的作用域和实例属性,但不允许使用 C 或 C++ 静态变量进行一次性初始化。无论如何,我认为应该避免将可写类型常量作为一个古怪的历史脚注。
您可以使用全局变量。
var
dx: Integer;
dy: Integer
function UpdatePosition(x,y: Integer): Boolean;
begin
if (x+dx < 0) or (x+dx > 640) then
dx := -dx;
...
MoveObject(x+dx, y+dy);
...
end;
您必须在中进行一次性初始化initialization
部分:
initialization
dx := Trunc( Power(-1, Random(2)) );
dy := Trunc( Power(-1, Random(2)) );
当然,与 C 静态变量的有限范围不同,这会使全局命名空间变得混乱。在现代 Delphi 中,您可以将其全部包装在一个类中,并使用类方法、类变量的组合,类构造函数 http://docwiki.embarcadero.com/RADStudio/en/Methods#Class_Constructors以避免污染全局名称空间。
type
TPosition = class
private class var
dx: Integer;
dy: Integer;
private
class constructor Create;
public
class function UpdatePosition(x,y: Integer): Boolean; static;
end;
class constructor TPosition.Create;
begin
dx := Trunc( Power(-1, Random(2)) );
dy := Trunc( Power(-1, Random(2)) );
end;
class function TPosition.UpdatePosition(x,y: Integer): Boolean;
begin
// your code
end;