考虑:
function OuterFunc: integer;
function InnerFunc: integer;
begin
// Here I'd like to access the OuterFunc.Result variable
// for both reading and writing its value
OuterFunc.Result := OuterFunc.Result + 12;
end;
begin
end;
是否有本地语法来访问 InnerFunc 内的 OuterFunc Result 变量?或者是像参数一样传递它的唯一方法,如下所示?
function OuterFunc: integer;
function InnerFunc(var outerResult: integer): integer;
begin
end;
var
i: integer;
begin
i := InnerFunc(Result);
end;
最佳答案
你可以通过给函数名赋值来给函数赋值,这实际上是 Pascal 中最原始的方式:
function MyFunc: integer;
begin
MyFunc := 2;
// is equal to the following
Result := 2;
end;
所以在你的情况下你可以写
function OuterFunc: integer;
function InnerFunc: integer;
begin
OuterFunc := 12;
end;
begin
end;
但是请注意,在语句 block 中使用赋值运算符左侧以外的函数名称会导致递归调用,因此与预定义的 Result
的工作方式不同。
换句话说,您无法从 InnerFunc
内部访问先前设置的 OuterFunc
值。您需要使用例如在 InnerFunc
之前定义的外部作用域中的局部变量也可以从 InnerFunc 访问:
function OuterFunc: integer;
var
OuterResult: integer;
function InnerFunc: integer;
begin
OuterResult := 0;
OuterResult := OuterResult + 12;
end;
begin
Result := OuterResult;
end;
有关更多详细信息,请参阅 the documentation 中的函数声明
.
关于delphi - Delphi 中是否有从内部函数访问外部函数 Result 变量的 native 语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43274080/