如何访问具有相同名称的父属性

Dan*_*ula 0 delphi setter inheritance properties

我需要在我的表单的FormStyle属性更改之前进行一些处理,但TForm.SetFormStyle(属性setter)是私有的,是否有某种方法来覆盖属性但仍然可以访问父类属性?

TMyForm = class(TForm)
private
  procedure MySetFormStyle(Style: TFormStyle);
public
  property FormStyle: TFormStyle read Parent.FormStyle write MySetFormStyle;
end;

TMyForm.MySetFormStyle(Style: TFormStyle);
begin
  if Parent.FormStyle <> Style then
    DoSomething;

  Parent.FormStyle := Style; 
end;
Run Code Online (Sandbox Code Playgroud)

我正在使用delphi 2010

Dav*_*nan 6

这会创建一个新属性而不是覆盖现有属性.事实上,不可能覆盖属性.如果SetFormStyle是虚拟的,那么你可以覆盖setter.

您可以访问继承的属性.像这样:

type
  TMyForm = class(TForm)
  private
    function GetFormStyle: TFormStyle;
    procedure SetFormStyle(Value: TFormStyle);
  public
    property FormStyle: TFormStyle read GetFormStyle write SetFormStyle;
  end;

function TMyForm.GetFormStyle: TFormStyle;
begin
  Result := inherited FormStyle;
end;

procedure TMyForm.SetFormStyle(Value: TFormStyle);
begin
  if Value <> FormStyle then
  begin
    DoSomething;
    inherited FormStyle := Value; 
  end;
end;
Run Code Online (Sandbox Code Playgroud)

这样做的问题是您的属性不会替换TForm.dfm文件中的属性.读取.dfm文件时,请FormStyle引用该TForm属性.如果您有对a的引用,则可以在运行时设置属性TMyForm.

因此,虽然上面的代码将编译,但我不认为它会解决您的问题.我已经回答了如何从派生类访问继承属性的直接问题,但我不认为我已经解决了你的实际问题.

我的直觉是你提出的设计和上面的代码是一个坏主意.由于修改表单样式将导致窗口重新创建,您可能真正需要的是覆盖CreateParamsCreateWnd.