delphi – 传递接口的方法作为参数
发布时间:2020-12-15 04:31:01 所属栏目:大数据 来源:网络整理
导读:可以将接口的方法作为参数传递吗? 我正在尝试这样的事情: interfacetype TMoveProc = procedure of object; // also tested with TMoveProc = procedure; // procedure of interface is not working ;) ISomeInterface = interface procedure Pred; proced
可以将接口的方法作为参数传递吗?
我正在尝试这样的事情: 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; 但它不工作,因为:
当然,我可以为每个电话做私人方法,但那是丑陋的.有没有更好的方法? 德尔福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的访客.现在我使用简单(“丑”)包装(我自己的,同样的解决方案由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; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |