可以将接口的方法作为参数传递吗?
我正在尝试这样的事情:
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;@H_404_5@但它不工作,因为:
E2010 Incompatible types: ‘TMoveProc’ and ‘procedure,untyped pointer or untyped parameter’
@H_403_11@当然,我可以为每个电话做私人方法,但那是丑陋的.有没有更好的方法?
德尔福2006
编辑:
我知道我可以通过整个界面,但是我必须指定哪个功能使用.我不需要两个完全相同的程序与一个不同的呼叫.我可以使用第二个参数,但也是丑陋的.
type SomeInterfaceMethod = (siPred,siNext) procedure Move(SomeInt: ISomeInterface; Direction: SomeInterfaceMethod) begin case Direction of: siPred: SomeInt.Pred; siNext: SomeInt.Next end; end;@H_404_5@感谢所有的帮助和想法.清洁的解决方案(对于我的Delphi 2006)是Diego的访客.现在我使用简单(“丑”)包装(我自己的,同样的解决方案由TOndrej和Aikislave).
但是真正的答案是“没有(直接)方式将接口的方法作为参数传递,而没有某种提供者.
解决方法
这是在Delphi 20006中工作的另一个解决方案.它类似于@Rafael的想法,但是使用接口:
interface type ISomeInterface = interface //... end; IMoveProc = interface procedure Move; end; IMoveProcPred = interface(IMoveProc) ['{4A9A14DD-ED01-4903-B625-67C36692E158}'] end; IMoveProcNext = interface(IMoveProc) ['{D9FDDFF9-E74E-4F33-9CB7-401C51E7FF1F}'] end; TSomeObject = class(TObject) public procedure Move(MoveProc: IMoveProc); end; TImplementation = class(TInterfacedObject,ISomeInterface,IMoveProcNext,IMoveProcPred) procedure IMoveProcNext.Move = Next; procedure IMoveProcPred.Move = Pred; procedure Pred; procedure Next; end; implementation procedure TSomeObject.Move(MoveProc: IMoveProc); begin while True do begin // Some common code that works for both procedures MoveProc.Move; // More code... end; end; procedure Usage; var o: TSomeObject; i: ISomeInterface; begin o := TSomeObject.Create; i := TImplementation.Create; o.Move(i as IMoveProcPred); // somewhere else: o.Move(i as IMoveProcNext); o.Free; end;@H_404_5@