是否可以将接口(interface)的方法作为参数传递?
我正在尝试这样的事情:
interface
type
TMoveProc = procedure of object;
// also tested with TMoveProc = procedure;
// procedure of interface is not working ;)
ISomeInterface = interface
procedure Pred;
procedure Next;
end;
TSomeObject = class(TObject)
public
procedure Move(MoveProc: TMoveProc);
end;
implementation
procedure TSomeObject.Move(MoveProc: TMoveProc);
begin
while True do
begin
// Some common code that works for both procedures
MoveProc;
// More code...
end;
end;
procedure Usage;
var
o: TSomeObject;
i: ISomeInterface;
begin
o := TSomeObject.Create;
i := GetSomeInterface;
o.Move(i.Next);
// somewhere else: o.Move(i.Prev);
// tested with o.Move(@i.Next), @@... with no luck
o.Free;
end;
但它不起作用,因为:
E2010 Incompatible types: 'TMoveProc' and 'procedure, untyped pointer or untyped parameter'
当然,我可以为每个调用执行私有(private)方法,但这很丑陋。还有更好的办法吗?
德尔福2006
<小时/>编辑: 我知道我可以传递整个接口(interface),但是我必须指定使用哪个函数。我不希望两个完全相同的过程具有一个不同的调用。
我可以使用第二个参数,但这也很难看。
type
SomeInterfaceMethod = (siPred, siNext)
procedure Move(SomeInt: ISomeInterface; Direction: SomeInterfaceMethod)
begin
case Direction of:
siPred: SomeInt.Pred;
siNext: SomeInt.Next
end;
end;
<小时/>
感谢大家的帮助和想法。干净的解决方案(对于我的 Delphi 2006)是迭戈的访客。现在我使用简单(“丑陋”)的包装器(我自己的,TOndrej 和 Aikislave 的相同解决方案)。
但真正的答案是“如果没有某种提供者,就没有(直接)方法将接口(interface)的方法作为参数传递。
最佳答案
如果您使用的是 Delphi 2009,则可以使用匿名方法来执行此操作:
TSomeObject = class(TObject)
public
procedure Move(MoveProc: TProc);
end;
procedure Usage;
var
o: TSomeObject;
i: ISomeInterface;
begin
o := TSomeObject.Create;
i := GetSomeInterface;
o.Move(procedure() begin i.Next end);
尝试仅传递对接口(interface)方法的引用的问题是,您没有传递对接口(interface)本身的引用,因此无法对接口(interface)进行引用计数。但匿名方法本身是引用计数的,因此这里匿名方法内部的接口(interface)引用也可以进行引用计数。这就是这个方法有效的原因。
关于delphi - 将接口(interface)的方法作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/704980/