gpt4 book ai didi

delphi - 如何用 2 个或更多类实现相同的方法?

转载 作者:行者123 更新时间:2023-12-03 14:55:59 24 4
gpt4 key购买 nike

我想编写一个具有 3 个相同方法的 TCheckBoxTRadioButton 后代。

TMyCheckBox = class(TCheckBox)
procedure DoSomething1;
procedure DoSomething2;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
end;

TMyRadioButton = class(TRadioButton)
procedure DoSomething1;
procedure DoSomething2;
procedure WMSize(var Message: TWMSize); message WM_SIZE;
end;

// the following procedures are common for both classes, so in fact
// TMyCheckBox.DoSomething1 do the same as TMyRadioButton.DoSomething1

procedure DoSomething1;
begin
// here is the same code for TMyCheckBox as well as for TMyRadioButton
// but I don't want to write the same code many times but implement it
// for both classes at once in some common way
end;

procedure DoSomething2;
begin
// here is the same code for TMyCheckBox as well as for TMyRadioButton
// but I don't want to write the same code many times but implement it
// for both classes at once in some common way
end;

procedure WMSize(var Message: TWMSize); message WM_SIZE;
begin
// here is the same code for TMyCheckBox as well as for TMyRadioButton
// but I don't want to write the same code many times but implement it
// for both classes at once in some common way
end;

我该怎么做?

最佳答案

使用三个方法签名定义一个接口(interface),例如IDoSomething

然后将您的类声明更改为

TMyCheckBox = class(TCheckBox, IDoSomething)

然后实现。

实现是否常见或非常接近。

然后定义一个辅助类TDoSomething,然后委派工作。

例如

Procedure TMyCheckBox.DoSomething1; // implements IDoSomething1
Begin
TDoSomething.DoSomething1(Self); // given class method will suffice.
End;

delphi中的类方法,相当于其他语言中的静态方法。

Type
TDoSomethingHelper = Class(TObject)
Public
Class Procedure DoSomething1(aComponent : TComponent);
End;

...
implementation

Class Procedure TDoSomethingHelper.DoSomething1(aComponent : TComponent);
Begin
aComponent.Tag = 27;
End;

关于delphi - 如何用 2 个或更多类实现相同的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8804577/

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