gpt4 book ai didi

c# - 深入探讨关闭的实现

转载 作者:太空狗 更新时间:2023-10-29 23:06:35 24 4
gpt4 key购买 nike

考虑以下代码块:

int x = 1;
D foo = () =>
{
Console.WriteLine(x);
x = 2;
};

x = 3;
foo();
Console.WriteLine(x);

输出是:3,2。我试图了解这段代码运行时幕后发生的事情。

编译器生成这个新类: enter image description here

x 变量如何改变的问题。 <>_DiplayClass1 中的 x 如何改变 Program 类中的 x。它在幕后做这样的事情吗?

var temp = new <>c_DisplayClass1();
temp.x = this.x;
temp.<Main>b_0();
this.x = temp.x;

最佳答案

如果您查看 Main 中发生的情况,您会看到:

public static void Main(string[] args)
{
Program.<>c__DisplayClass0_0 <>c__DisplayClass0_ = new Program.<>c__DisplayClass0_0();
<>c__DisplayClass0_.x = 1;
Action action = new Action(<>c__DisplayClass0_.<Main>b__0);
<>c__DisplayClass0_.x = 3;
action();
Console.WriteLine(<>c__DisplayClass0_.x);
}

[CompilerGenerated]
private sealed class <>c__DisplayClass0_0
{
public int x;

internal void <Main>b__0()
{
Console.WriteLine(this.x);
this.x = 2;
}
}

这让事情变得更加清晰。您会看到被提升的 x 成员被设置了两次,一次是 1,然后是 3。在 b__0 中,它再次设置为 2。因此,您会看到实际更改发生在 同一成员 上。这就是关闭变量时发生的情况。 实际变量被提升,而不是它的值。

关于c# - 深入探讨关闭的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31586153/

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