gpt4 book ai didi

delphi - 匿名方法 - 变量捕获与值捕获

转载 作者:行者123 更新时间:2023-12-03 14:56:39 24 4
gpt4 key购买 nike

下面是基于第 1 部分的匿名方法部分中的示例的 SSCCEChris Rolliston 的优秀 Delphi XE2 Foundations 书籍,关于变量的概念捕获(其中的任何错误完全由我负责)。

它的工作原理完全符合我的预期,连续点击时会记录 666、667、668、669Btn调用按钮。特别是它很好地说明了捕获的版本是如何局部变量 I 在 btnSetUpClick 退出后仍然存在很长时间。

到目前为止一切顺利。我要问的问题不在于这段代码本身,而是在于Allen Bauer 的博客中是这样说的:

http://blogs.embarcadero.com/abauer/2008/10/15/38876

现在,我知道最好不要和老板争论,所以我确信我没有捕获要点他对变量捕获和值(value)捕获之间的区别进行了阐述。以我简单的方式仔细观察,我的基于 CR 的示例通过将 I 捕获为变量来捕获 I 的值。

所以,我的问题是,鲍尔先生到底想要区分什么?

(顺便说一句,尽管每天观看 SO 的 Delphi 部分已经 9 个多月了,但我仍然不完全了解明确这个问题是否切中主题。如果没有,我深表歉意,我会将其删除。)

type
TAnonProc = reference to procedure;

var
P1,
P2 : TAnonProc;

procedure TForm2.Log(Msg : String);
begin
Memo1.Lines.Add(Msg);
end;

procedure TForm2.btnSetUpClick(Sender: TObject);
var
I : Integer;
begin
I := 41;
P1 := procedure
begin
Inc(I);
Log(IntToStr(I));
end;

I := 665;
P2 := procedure
begin
Inc(I);
Log(IntToStr(I));
end;
end;

procedure TForm2.btnInvokeClick(Sender: TObject);
begin
Assert(Assigned(P1));
Assert(Assigned(P2));

P1;
P2;
end;

最佳答案

变量捕获与值捕获非常简单。让我们假设两个匿名方法捕获同一个变量。像这样:

Type
TMyProc = reference to procedure;
var
i: Integer;
P1, P2: TMyProc;
....
i := 0;
P1 := procedure begin Writeln(i); inc(i); end;
P2 := procedure begin Writeln(i); inc(i); end;
P1();
P2();
Writeln(i);

这两种方法都捕获一个变量。输出为:

012

This is capture of a variable. If the value was captured, which it isn't, one might imagine that the two methods would have separate variables that both started with value 0. And both functions might output 0.

In your example, you are supposed to imagine that P1 captures the value 41, and P2 captures the value 665. But that does not happen. There is exactly one variable. It is shared between the procedure that declares it, and the anonymous methods that capture it. It lives as long as all parties that share it live. Modifications to the variable made by one party are seen by all others because there is exactly one variable.


So, it is not possible to capture a value. To get behaviour that feels like that you need to copy a value to a new variable, and capture that new variable. That can be done with, for instance, a parameter.

function CaptureCopy(Value: Integer): TMyProc;
begin
Result := procedure begin Writeln(Value); end;
end;

...
P3 := CaptureCopy(i);

这会将 i 的值复制到一个新变量(过程参数)中,并捕获它。对 i 的后续更改对 P3 没有影响,因为捕获的变量是 P3 的本地变量。

关于delphi - 匿名方法 - 变量捕获与值捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24223428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com