gpt4 book ai didi

delphi - 继承类重写虚方法依赖

转载 作者:行者123 更新时间:2023-12-03 14:41:50 25 4
gpt4 key购买 nike

我有这两个类(class):

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我必须inherited TMyBaseClass.DoSomething但我希望它尊重 if not FAllowDoSomething then <don't do anything> .

我尝试过使用AbortTMyBaseClass但我意识到这不是一个好主意,并且会破坏调用方法( TForm1.Button1Click );

在不写 if not FAllowDoSomething then Exit 的情况下,执行此操作的正确方法是什么? 再次 TMyChildClass .

最佳答案

关键点是在基类中对 bool 值执行一次检查。因此,使 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;

关于delphi - 继承类重写虚方法依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19951525/

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