我们可以使用以下代码获取类方法地址:
type
TMyClass = class
procedure A;
end;
var P: Pointer;
begin
P := @TMyClass.A;
end;
Run Code Online (Sandbox Code Playgroud)
对于泛型类,如何从泛型类获取方法地址?
type
TGeneric<T> = class
procedure A;
end;
var P: Pointer;
begin
P := @TGeneric<T>.A; // <--- compilation error
end.
Run Code Online (Sandbox Code Playgroud)
TGeneric<T>是开放类型,换句话说,并非所有类型参数都已指定。您的代码失败,因为开放类型的方法没有单个地址。不同的具体实例具有不同的地址。例如,与的TGeneric<Integer>.A方法不同TGeneric<string>.A,因此地址也不同。
除非您为泛型类型参数提供具体的值,否则此构造将没有任何意义。考虑以下程序:
{$APPTYPE CONSOLE}
type
TGeneric<T> = class
class procedure A;
end;
class procedure TGeneric<T>.A;
var
P: Pointer;
begin
P := @TGeneric<T>.A;
Writeln(NativeInt(P));
end;
begin
TGeneric<Integer>.A;
TGeneric<string>.A;
end.
Run Code Online (Sandbox Code Playgroud)
该程序输出两个不同的值。
| 归档时间: |
|
| 查看次数: |
77 次 |
| 最近记录: |