是否可以将接口的方法作为参数传递?
我正在尝试这样的事情:
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 不兼容的类型:“TMoveProc”和“过程、无类型指针或无类型参数”
当然我可以为每个调用做私有方法,但这很难看。有没有更好的办法?
德尔福 2006
编辑:我知道我可以通过整个界面,但是我必须指定使用哪个函数。我不想要两个完全相同的程序和一个不同的调用。
我可以使用第二个参数,但这也很难看。
type
SomeInterfaceMethod = (siPred, siNext)
procedure Move(SomeInt: ISomeInterface; Direction: SomeInterfaceMethod)
begin
case Direction of:
siPred: SomeInt.Pred;
siNext: SomeInt.Next
end;
end;
感谢大家的帮助和想法。干净的解决方案(对于我的 Delphi 2006)是 Diego's Visitor。现在我正在使用简单的(“丑陋”)包装器(我自己的,由 TOndrej 和 Aikislave 提供的相同解决方案)。
但真正的答案是“没有某种提供者,就没有(直接)方法可以将接口的方法作为参数传递。