当没有外部上下文时,过程变量和匿名函数是否等效?
据我所知,当在匿名过程中提到外部变量时,需要采取特殊措施来维护外部变量的生命周期。但是,当匿名过程不使用外部变量时,它是否会生成与旧的通用过程相同的汇编调用。换句话说,片段 1 中的匿名函数和片段 2 中的 NamedFunction 的内部结构是否相同
片段 1
type
TSimpleFunction = reference to function(x: string): Integer;
begin
y1 := function(x: string): Integer
begin
Result := Length(x);
end;
y1('test');
end.
片段 1
type
TWellKnownSimpleFunction = function(x: string): Integer;
function NamedFunction(x: string): Integer;
begin
Result := Length(x);
end;
var
y1: TWellKnownSimpleFunction;
begin
y1:=NamedFunction;
y1('test');
end.
I understand that there are special actions to maintaining the lifetime of a outer variable when it was mentioned inside an anonymous procedure. But when the anonymous procedure doesn't use outer variables, will it generate the same assembly call as the good old general procedure. In other words, will the internals of the anonymous function in the Fragment 1 and NamedFunction from fragment 2 be the same
Fragment 1
type
TSimpleFunction = reference to function(x: string): Integer;
begin
y1 := function(x: string): Integer
begin
Result := Length(x);
end;
y1('test');
end.
Fragment 1
type
TWellKnownSimpleFunction = function(x: string): Integer;
function NamedFunction(x: string): Integer;
begin
Result := Length(x);
end;
var
y1: TWellKnownSimpleFunction;
begin
y1:=NamedFunction;
y1('test');
end.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不会。匿名方法在内部作为接口引用实现。有关详细信息,请阅读 Barry Kelly 的文章。
您还可以查看我的文章 我尝试用接口来模仿匿名
方法。
匿名方法不是过程变量,即使它们不捕获变量。
No. Anonymous methods are implemented internally as interface references. Read Barry Kelly's article for details.
You can also look at my article where I experimenting with interfaces to mimic anonymous
methods.
Anonymous methods are not procedural variables, even if they does not capture variables.