如何将另一个函数返回的函数分配给函数变量?结果而不是生成函数本身 [英] How to assign a function, returned by another function, to a function variable? The result rather than the generating function itself
问题描述
一个函数正在返回一个匿名函数.我想将结果分配给一个变量.但是,编译器认为我正在尝试分配函数,而不是函数的结果.我该如何解决?
A function is returning an anonymous function. I would like to assign the result to a variable. However the compiler thinks that I am trying to assign the function and not the result of the function. How can I resolve this?
program Project9;
{$APPTYPE CONSOLE}
type
TMyEvent = reference to function: string;
var
v1: TMyEvent;
function GetHandler: TMyEvent;
begin
Result := function: string
begin
Result := '';
end;
end;
begin
v1 := GetHandler; // <- Incompatible types: 'TMyEvent' and 'Procedure'
end.
注意:我确实有一种解决方法,但我希望可以在不引入包装器的情况下解决此问题:
Note: I do have a workaround but I hope that this problem can be solved without introducing a wrapper:
program Project9;
{$APPTYPE CONSOLE}
type
TMyEvent = reference to function: string;
TWrapper = record
FHandler: TMyEvent;
end;
var
v1: TMyEvent;
function GetHandler: TWrapper;
begin
Result.FHandler := function: string
begin
Result := '';
end;
end;
begin
v1 := GetHandler.FHandler; // <- works
这并非特定于匿名函数或任何特殊类型的函数:对于返回该函数的任何函数都是实际的,甚至在第一个Delphi到达之前,它在Turbo Pascal中都是相同的.
推荐答案
如果您的匿名方法/函数是无参数的,则必须分配();
If your anonymous methods/functions are paramless, you must assign with ();
v1 := GetHandler();
在没有括号的情况下,Delphi将尝试将功能分配给变量.括号告诉它调用该函数并将函数结果分配给该变量.
Without the parentheses Delphi will try to assign the function to the variable. The parens tell it to invoke the function and assign the function result to the variable.
这篇关于如何将另一个函数返回的函数分配给函数变量?结果而不是生成函数本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!