如果未设置 属性 则生成编译器错误

Generate compiler error if property is not set

如果我的对象中的某个 属性 未设置,我希望能够创建一个编译器 error/warning。假设我有以下 class:

interface

type
  TBarkevent = procedure (Bark : String) of object;

  TDog = class
  private
    FOnBark : TBarkevent;
    procedure SetBark(const Value: TBarkevent);
    function GetBark: TBarkEvent;
  public
    procedure Bark;
    property OnBark : TBarkEvent read GetBark write SetBark;
    constructor Create;
  end;

implementation

{ TDog }

procedure TDog.Bark;
begin
  if Assigned(OnBark) then
    OnBark('Woof!')
end;

constructor TDog.Create;
begin
end;

function TDog.GetBark: TBarkEvent;
begin
  Result := FOnBark;
end;

procedure TDog.SetBark(const Value: TBarkevent);
begin
  FOnBark := Value;
end;

我在另一个单元中使用 TDog class 是这样的:

var
  Dog : TDog;
begin
  Dog := TDog.Create;
  Dog.OnBark := DogBark;
  Dog.Bark;

现在,一旦调用 Bark() 过程,就会触发 OnBark 事件。

我的问题:

我是否可以强制指定OnBark属性,以便在以下情况下发出编译器error/warning活动未设置?

将您的 class 定义为:

TDog = class
private
  FOnBark : TBarkevent;
  procedure SetBark(const Value: TBarkevent);
  function GetBark: TBarkEvent;
public
  procedure Bark;
  property OnBark : TBarkEvent read GetBark write SetBark;
  constructor Create(Bark : TBarkEvent);
end;

这样,您无法在不指定事件的情况下实例化 TDog 对象。如果你尝试,你会得到一个编译器错误。

首先:不。不可能在编译时检查这样的属性。

几乎强制实现OnBark事件,您可以将其添加为构造函数参数,而不是将其发布为 read/write-property。然后,您可以使用 Assert() 在 运行 时检查它,在调用构造函数时是否已将有效的回调方法传递给构造函数。

要使其真正强制,您可以声明以下内容:

TCustomDog = class
public
  procedure Bark; virtual; abstract;
end;

因此,每个使用 TCustomDog class 的人都必须执行 Bark 程序。如果他不这样做,将发出编译器警告。