在Delphi中如何传递函数作为参数?

前端之家收集整理的这篇文章主要介绍了在Delphi中如何传递函数作为参数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
可以在过程中传递一个对象函数作为参数,而不是传递整个对象吗?

我有一个记录定义,函数定义为一个公共类参数,如:

TMyRecord = record
      public
        class function New(const a,b: Integer): TMyRecord; static;
        function GiveMeAValue(inputValue: integer): Single;
      public
        a,b: Integer;
      end;

功能可以是:

function TMyRecord.GiveMeAValue(inputValue: Integer): Single;
    begin
      RESULT := inputValue/(self.a + self.b);
    end;

然后我希望定义一个调用函数GiveMeAValue的过程,但是我不想将整个记录传递给它.我可以这样做,例如:

Procedure DoSomething(var1: Single; var2,var3: Integer,?TMyRecord.GiveMeAValue?);
    begin
      var1 = ?TMyRecord.GiveMeAValue?(var2 + var3);
      //Do Some Other Stuff
    end;

如果是这样,那么如何正确地传递函数作为过程参数?

@H_502_16@

解决方法

您可以为函数定义新的类型
TGiveMeAValue= function(inputValue: integer): Single of object;// this definition works fine for methods for records.

然后定义DoSomething方法

Procedure DoSomething(var1: Single; var2,var3: Integer;GiveMeAValue: TGiveMeAValue);
begin
  writeln(GiveMeAValue(var2 + var3));
end;

并使用如此

var
  L : TMyRecord;
begin
    l.a:=4;
    l.b:=1;
    DoSomething(1,20,5,L.GiveMeAValue);
end;
@H_502_16@ @H_502_16@ 原文链接:https://www.f2er.com/delphi/101323.html

猜你在找的Delphi相关文章