gpt4 book ai didi

delphi - 调整实例类内存分配的大小

转载 作者:行者123 更新时间:2023-12-03 15:56:29 26 4
gpt4 key购买 nike

我使用此示例在运行时更改类:

procedure PatchInstanceClass(Instance: TObject; NewClass: TClass);
type
PClass = ^TClass;
begin
if Assigned(Instance) and Assigned(NewClass)
and NewClass.InheritsFrom(Instance.ClassType)
and (NewClass.InstanceSize = Instance.InstanceSize) then
begin
PClass(Instance)^ := NewClass;
end;
end;

type
TMyButton = class(TButton)
Private
FLogEvent : TNotifyEvent;
public
Property Log : TNotifyEvent Read FLogEvent Write FLogEvent;
procedure Click; override;
end;

procedure TMyButton.Click;
begin
Inherited;
if Assigned(FLogEvent) then
FLogEvent(Self);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
PatchInstanceClass(Button1, TMyButton);
end;

我的问题是 TMyButton 大小与 TButton 不同,因为我将其添加到 TMyButton 的 NotifyEvent 中。我的问题是如何调整 NewClass 同一实例的内存分配大小。 :-)

最佳答案

虽然我同意其他人的观点 - 你应该重新考虑你的方法,因为这听起来有点老套。不过,我喜欢一些古怪的东西 - 所以我将向您展示如何实现您所要求的目标。

关键是不要将任何内容放入新类中(因为 InstanceSize 需要相同),而应将其放在其他位置 - 如果您使用的是较新的 Delphi 版本(2010 或更高版本),您可以这样做。否则你需要稍微修改一下代码,但我想你明白了:

uses
Generics.Collections;

procedure PatchInstanceClass(Instance: TObject; NewClass: TClass);
begin
if Assigned(Instance) and Assigned(NewClass)
and NewClass.InheritsFrom(Instance.ClassType)
and (NewClass.InstanceSize = Instance.InstanceSize) then
begin
PPointer(Instance)^ := NewClass;
end;
end;

type
TMyButton = class(TButton)
private
function GetLogEvent: TNotifyEvent;
procedure SetLogEvent(const Value: TNotifyEvent);
public
destructor Destroy; override;
procedure Click; override;

property LogEvent: TNotifyEvent read GetLogEvent write SetLogEvent;
end;

TMyButtonHelper = class helper for TMyButton
private
class var fLogEvents: TDictionary<TObject, TNotifyEvent>;
public
class constructor Create;
class destructor Destroy;
end;

{ TMyButtonHelper }

class constructor TMyButtonHelper.Create;
begin
fLogEvents := TDictionary<TObject, TNotifyEvent>.Create;
end;

class destructor TMyButtonHelper.Destroy;
begin
fLogEvents.Free;
end;

{ TMyButton }

destructor TMyButton.Destroy;
begin
fLogEvents.Remove(Self);
inherited;
end;

procedure TMyButton.Click;
begin
inherited;
if Assigned(LogEvent) then
LogEvent(Self);
end;

function TMyButton.GetLogEvent: TNotifyEvent;
begin
fLogEvents.TryGetValue(Self, Result);
end;

procedure TMyButton.SetLogEvent(const Value: TNotifyEvent);
begin
fLogEvents.AddOrSetValue(Self, Value);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
PatchInstanceClass(Button1, TMyButton);
TMyButton(Button1).LogEvent := Button1Click;
end;

关于delphi - 调整实例类内存分配的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20441260/

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