【发布时间】:2010-10-16 20:10:06
【问题描述】:
接口的方法可以作为参数传递吗?
我正在尝试这样的事情:
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 提供的相同解决方案)。
但真正的答案是“没有某种提供者,没有(直接)方法可以将接口的方法作为参数传递。
【问题讨论】:
-
TSomeObject.Move 中的代码看起来像是“策略”模式的用例。 MoveProc 可以是 TAbstractMoveProcStrategy 类的方法,其中子类在 Move 方法中实现所需的行为。 TMovePredStrategy / TMoveNextStrategy 会有不同的 Move procs。
标签: delphi oop interface callback