gpt4 book ai didi

Delphi - 如何检查方法变量?

转载 作者:行者123 更新时间:2023-12-02 16:35:23 25 4
gpt4 key购买 nike

在 Delphi(我使用的是 D7)中,如何检查方法变量是否已分配给某些内容?我已经尝试过这段代码

function MethodIsOK(M : TMethod) : Boolean;
begin
//Result := M <> Nil;
//Result := Assigned(M);
end;

但是无论哪种分配 Result 都会给出“不兼容类型”编译错误

最佳答案

TMethod基于方法的指针被传递给内在的 Assigned()函数,它返回是否TMethod.Code字段不为零,无论 TMethod.Data 为何字段(您可以在无效的对象指针上调用对象方法),例如:

function MethodIsOK(M : TMethod) : Boolean;
begin
//Result := Assigned(M);
Result := M.Code <> nil;
end;

Allen Bauer 在博客中讨论了这个问题及其原因 Assigned()引入方法指针以支持设计时代码:

Assigned or not Assigned, that is the question…

The implementation of a method pointer for native code (Win16 and Win32, and the upcomming Win64 implementation), consists of two pointers. One points to the address of the method and the other to an object instance. It turns out that the simple if methodpointer <> nil then statement would check that both pointers were nil, which seems logical, right? And it is. However, there is a bit of a hitch here. At design-time, the native VCL form designer pulls a few tricks out of its hat. We needed a way to somehow assign a value to a component’s method pointer instance, but also make sure the component didn’t actually think anything was assigned to it and promptly try and call the method (BOOM!!). Enter, Assigned. By adding the standard function, Assigned, we could preserve the <> nil sematics, and also introduce a twist. It turns out, and for the adventurous among you can verify this, that Assigned only checks one of the two pointers in a method pointer. The other pointer is never tested. So what happens is that when you "assign" a method to the method pointer from within the IDE’s Object Inspector, the designer is actually jamming an internally created index into the other (non-Assigned-tested) pointer within the method pointer structure. So as long as your component uses if Assigned(methodpointer) then before calling through the method pointer, your component code will never misbehave at design-time.

关于Delphi - 如何检查方法变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35159025/

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