现在的位置: 首页 > 综合 > 正文

delphi中函数指针的用法

2017年12月02日 ⁄ 综合 ⁄ 共 788字 ⁄ 字号 评论关闭

  
    delphi中可以通过函数指针把一个函数作为参数来传递,然后在另外一个函数中调用。

    1) 首先,申明函数指针类型TFunctionParameter。

       type
          TFunctionParameter = function(const value : integer) : string;

     2) 定义准备被作为参数传递的函数

         function One(const value : integer) : string;
         begin
            result := IntToStr(value) ;
         end;

         function Two(const value : integer) : string;
         begin
            result := IntToStr(2 * value) ;
         end;
     
     3) 定义将要使用动态函数指针参数的函数

        function DynamicFunction(f : TFunctionParameter; const value : integer) : string;
        begin
           result := f(value) ;
        end;

      4) 上面这个动态函数的使用实例

        var
           s : string;
        begin
           s := DynamicFunction(One,2006) ;
           ShowMessage(s) ; //will display "2006"

           s := DynamicFunction(Two,2006) ;
           ShowMessage(s) ; // will display "4012"
        end;

 

 

抱歉!评论已关闭.