如何在方法指针中存储接口方法?

sta*_*wer 5 delphi delegates interface

有一个例子:

type
  TDelegate = procedure of object;

  I1 = interface
  ['{31D4A1C7-668B-4969-B043-0EC93B673569}']
    procedure P1;
  end;

  TC1 = class(TInterfacedObject, I1)
    procedure P1;
  end;

...

var
  obj: TC1;
  int: I1;
  d: TDelegate;
begin
  obj := TC1.Create;
  ...
  int := obj; // "int" may contains TSomeAnotherObjectWhichImplementsI1
  d := obj.P1; // <- that's fine
  d := int.P1; // <- compiler error
end;
Run Code Online (Sandbox Code Playgroud)

那我怎么做最后一次操作呢?我不知道哪个类型的对象将出现在"int"变量中,所以我不能使用类型转换.但我知道它会出现什么(因为如果你实现了一个接口,你必须实现它的所有方法).那么为什么我不能只获得指向这种方法的指针呢?也许有另一种方式?谢谢.

Dav*_*nan 2

我想编译器阻止它的至少一个原因是它procedure of object不是托管类型,因此您将绕过接口引用计数。

不允许这样做的另一个原因是接口方法的调用机制与procedure of object.