Loosen “Local procedure/function assigned to procedure variable” restriction gracefully

后端 未结 4 1182
臣服心动
臣服心动 2020-12-31 19:30

Consider the following test-case:

{ CompilerVersion = 21 }
procedure Global();

  procedure Local();
  begin
  end;

type
  TProcedure = procedure ();
var
           


        
4条回答
  •  猫巷女王i
    2020-12-31 19:52

    Here's why you can't do it:

    type
      TProcedure = procedure ();
    
    function Global(): TProcedure;
    var
      localint: integer;
    
      procedure Local();
      begin
        localint := localint + 5;
      end;
    
    begin
      result := Local;
    end;
    

    Local procedures have access to the outer routine's variable scope. Those variables are declared on the stack, though, and become invalid once the outer procedure returns.

    However, if you're using CompilerVersion 21 (Delphi 2010), you've got anonymous methods available, which should be able to do what you're looking for; you just need a slightly different syntax.

提交回复
热议问题