Sunday, October 20, 2019
Use a Function as a Parameter in Another Function
Use a Function as a Parameter in Another Function In Delphi, procedural types (method pointers) allow you to treat procedures and functions as values that can be assigned to variables or passed to other procedures and functions. Heres how to call a function (or procedure) as a parameter of another function (or procedure) : Declare the function (or procedure) that will be used as a parameter. In the example below, this is TFunctionParameter.Define a function that will accept another function as a parameter. In the example below this is DynamicFunction type à à TFunctionParameter function(const value : integer) : string;...function One(const value : integer) : string;begin à à result : IntToStr(value) ; end;function Two(const value : integer) : string;begin à à result : IntToStr(2 * value) ; end;function DynamicFunction(f : TFunctionParameter) : string;begin à à result : f(2006) ; end;...//Example usage: var à às : string; begin à às : DynamicFunction(One) ; à à ShowMessage(s) ; //will display 2006 à às : DynamicFunction(Two) ; à à ShowMessage(s) ; // will display 4012end; Important Notes Of course, you decide on the signature of the TFunctionParameter: whether it is a procedure or a function, how many parameters does it take, etc.If TFunctionParameter is a method (of an instance object) you need to add the words of object to the procedural type name, as in:TFunctionParameter function(const value : integer) : string of object;If you expect nil to be specified as the f parameter, you should test for this using the Assigned function.Fixing the Incompatible type: method pointer and regular procedure
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.