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

Tro*_*ian 12 delphi procedure function record parameter-passing

是否可以将对象函数作为参数传递给过程而不是传递整个对象?

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

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

该功能可能是这样的:

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

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

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

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

RRU*_*RUZ 21

您可以为函数定义新类型

TGiveMeAValue= function(inputValue: integer): Single of object;// this definition works fine for methods for records.
Run Code Online (Sandbox Code Playgroud)

然后定义方法 DoSomething

Procedure DoSomething(var1: Single; var2, var3: Integer;GiveMeAValue: TGiveMeAValue);
begin
  writeln(GiveMeAValue(var2 + var3));
end;
Run Code Online (Sandbox Code Playgroud)

并使用这样的

var
  L : TMyRecord;
begin
    l.a:=4;
    l.b:=1;
    DoSomething(1, 20, 5, L.GiveMeAValue);
end;
Run Code Online (Sandbox Code Playgroud)

  • Anon方法使代码更加灵活.但是,它们可能会让人头疼.不要在没有时间的情况下拒绝它们,但如果你在程序的瓶颈区域使用anon方法,你可能会受到影响. (3认同)
  • 或者,可以使用匿名方法.这可以让你在匿名方法中调用你喜欢的任何函数.http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devcommon/anonymousmethods_xml.html (2认同)