Delphi - 如何检查方法变量?

Delphi - how to check method variable?

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

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

但是任何一种分配方式 Result 都会产生“不兼容类型”编译错误

该方法包含代码和数据指针,您可以检查指针是否有效

当一个基于 TMethod 的方法指针被传递给内部 Assigned() 函数时,returns TMethod.Code 字段是否为非 nil,无论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.