gpt4 book ai didi

delphi - 负属性默认值似乎不起作用

转载 作者:行者123 更新时间:2023-12-03 18:09:13 25 4
gpt4 key购买 nike

当我安装该组件时,我查看了对象检查器,StoppingCount 的值为 0!我需要的值为-1。在我的代码中,高于 -1 的任何值都会在该数字处停止 for 循环过程。

default 是否不适用于负数?

unit myUnit;

interface

uses
System.SysUtils, System.Classes;

type
TmyComponent = class(TComponent)
private
{ Private declarations }
FStoppingCount: integer;

protected
{ Protected declarations }
procedure ProcessIT();

public
{ Public declarations }

published
{ Published declarations }

property StoppingCount: integer read FStoppingCount write FStoppingCount default -1;
end;

procedure Register;

implementation

procedure Register;
begin
RegisterComponents('myComponent', [TmyComponent]);
end;

procedure TmyComponent.ProcessIT();
begin
for I := 0 to 1000 do
begin
DoSomething();
if FStoppingCount = I then break;
end;
end;

最佳答案

负值工作得很好。问题在于您实际上并未将 FStoppingCount 初始化为 -1,因此当创建组件的新实例并将其内存最初清零时,它会被初始化为 0。

仅仅在 property 声明中声明一个非零的 default 值是不够的。 default 值仅存储在属性的 RTTI 中,并且仅在将组件写入 DFM 时以及在对象检查器中显示属性值时用于比较目的。 default 指令实际上并不影响内存中组件的实例。您必须显式设置 FStoppingCount 的值以匹配 default 值。这在文档中有明确说明:

Properties (Delphi)

Note: Property values are not automatically initialized to the default value. That is, the default directive controls only when property values are saved to the form file, but not the initial value of the property on a newly created instance.

要修复您的组件,您需要添加一个将 FStoppingCount 初始化为 -1 的构造函数,例如:

unit myUnit;

interface

uses
System.SysUtils, System.Classes;

type
TmyComponent = class(TComponent)
private
{ Private declarations }
FStoppingCount: integer;
protected
{ Protected declarations }
procedure ProcessIT();
public
{ Public declarations }
constructor Create(AOwner: TComponent); override; // <-- ADD THIS!
published
{ Published declarations }
property StoppingCount: integer read FStoppingCount write FStoppingCount default -1;
end;

procedure Register;

implementation

procedure Register;
begin
RegisterComponents('myComponent', [TmyComponent]);
end;

constructor TmyComponent.Create(AOwner: TComponent);
begin
inherited;
FStoppingCount := -1; // <-- ADD THIS!
end;

procedure TmyComponent.ProcessIT();
begin
for I := 0 to 1000 do
begin
DoSomething();
if FStoppingCount = I then break;
end;
end;

关于delphi - 负属性默认值似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59438315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com