gpt4 book ai didi

delphi - 为什么我收到 E2356 属性访问器必须是实例字段或方法

转载 作者:行者123 更新时间:2023-12-03 15:42:13 26 4
gpt4 key购买 nike

编译本单元时:

unit Test;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;

type
TForm1 = class(TForm)
private
class var StartDate, EndDate: TDateTime; // Line 12
fTest: TNotifyEvent;
public
property OnTest: TNotifyEvent read fTest; // Line 15.
end;

implementation

{$R *.dfm}

end.

我收到以下编译器错误:

[DCC Error] Test.pas(15): E2356 Property accessor must be an instance field or method

但是如果我注释掉第 12 行,它编译得很好。有人可以解释为什么吗?我需要日期作为类变量来存储日期间隔。

最佳答案

该错误应该是不言自明的。让我们尝试解构它。

Property accessor must be an instance field or method.

属性访问器read后面的表达式。如果您的属性是可写的,那么 write 后面的表达式也将是属性访问器。

因此,在您的代码中,属性访问器是 fTest

实例字段是类的普通字段。因此,类字段不符合条件。同样,实例方法是类的普通方法。类方法不是实例方法。事实上,任何不是类方法的方法都是实例方法。

因此,该错误表明 fTest 不是实例字段。

这是正确的。这是一个类字段。

private
class var StartDate, EndDate: TDateTime;
fTest: TNotifyEvent; // class var applies to fTest also

我猜你的意思并不是让 fTest 成为一个类字段。您需要像这样编写类:

TForm1 = class(TForm)
private
class var StartDate, EndDate: TDateTime;
private
fTest: TNotifyEvent;
public
property OnTest: TNotifyEvent read fTest;
end;

或者也许:

TForm1 = class(TForm)
private
class var
StartDate, EndDate: TDateTime;
var
fTest: TNotifyEvent;
public
property OnTest: TNotifyEvent read fTest;
end;

我喜欢前者,因为它在类字段和实例字段之间提供了更清晰的区别。

关于delphi - 为什么我收到 E2356 属性访问器必须是实例字段或方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13256070/

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