加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

delphi – 继承的类覆盖虚拟方法依赖

发布时间:2020-12-15 04:22:05 所属栏目:大数据 来源:网络整理
导读:我有这两个班: type TMyBaseClass = class protected FAllowDoSomething: Boolean; // initialized to False procedure DoSomething; virtual; end; TMyChildClass = class(TMyBaseClass) protected procedure DoSomething; override; end;implementationpr
我有这两个班:
type
  TMyBaseClass = class
  protected
    FAllowDoSomething: Boolean; // initialized to False
    procedure DoSomething; virtual;
  end;

  TMyChildClass = class(TMyBaseClass)
  protected
    procedure DoSomething; override;
  end;

implementation

procedure TMyBaseClass.DoSomething;
begin
  if not FAllowDoSomething then Exit; // Abort;
  ShowMessage('TMyBaseClass: FAllowDoSomething is False. You wont see me!');
end;

procedure TMyChildClass.DoSomething;
begin
  inherited; // Must inherit
  // if not FAllowDoSomething then Exit; { I don't want to check here again }
  ShowMessage('TMyChildClass: FAllowDoSomething is False but still I can see this message!');
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  with TMyBaseClass.Create do try
    DoSomething;
  finally
    Free;
  end;    

  // if I use Abort in TMyBaseClass,the code will not get here

  with TMyChildClass.Create do try
    DoSomething;
  finally
    Free;
  end;
end;

在TMyChildClass.DoSomething中,我必须继承TMyBaseClass.DoSomething,但是我希望它遵守如果不是FAllowDoSomething然后<不做任何>.

我试过在TMyBaseClass中使用Abort,但是我意识到这不是一个好主意,并且会打破调用方法(TForm1.Button1Click);

这样做的正确方法是什么,没有写入,如果不是FAllowDoSomething然后再次退出在TMyChildClass.

解决方法

关键是在基类中对boolean执行一次检查.所以,使DoSomething非虚拟,并在您的基类中实现它,如下所示:
procedure TMyBaseClass.DoSomething;
begin
  if FAllowDoSomething then
    DoSomethingImplementation;
end;

其中DoSomethingImplementation是您在派生类中重写的虚拟方法.

基础类似如下:

type
  TMyBaseClass = class
  private
    FAllowDoSomething: Boolean;
  protected
    procedure DoSomethingImplementation; virtual;
  public
    procedure DoSomething;
  end;

你的派生类看起来像这样:

type
  TMyDerivedClass = class(TMyBaseClass)
  protected
    procedure DoSomethingImplementation; override;
  end;

您重写的方法如下所示:

procedure TMyDerivedClass.DoSomethingImplementation;
begin
  inherited;
  ShowMessage(...);
end;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读