2008. június 21., szombat
How to store a procedure or function in a variable
Problem/Question/Abstract:
Is there some way I can store a procedure or function in a variable so I can call the procedure with the variable? I'm thinking of something similar to where you can declare a variable of a certain object type, then assign different objects of that type to the variable. If it can be done with procedures, how would it be assigned and what would the syntax be to call the procedure?
Answer:
Yes, you can declare a procedural type for functions with the same parameter list and function type. Briefly it looks something like this:
{ ... }
type
TMathFunc = function(A, B: double): double; {defines signature of function}
{ ... }
var
mathfunc: TMathFunc;
answer: double;
{ ... }
{Now if you define two functions}
function Adder(A, B: double): double;
begin
result := A + B;
end;
function Multiplier(A, B: double): double;
begin
result := A * B;
end;
begin
{You can do this}
mathfunc := Adder;
answer := mathfunc(5, 9);
mathfunc := Multiplier;
answer := mathfunc(5, 9);
end;
Feliratkozás:
Megjegyzések küldése (Atom)
Nincsenek megjegyzések:
Megjegyzés küldése