gpt4 book ai didi

c# - 当一个变量被关闭两次时,它存储在哪里?

转载 作者:太空狗 更新时间:2023-10-30 01:30:55 25 4
gpt4 key购买 nike

我正在有趣地阅读这篇名为 C# Closures Explained 的文章,其中指出:

You see, the C# compiler detects when a delegate forms a closure which is passed out of the current scope and it promotes the delegate, and the associated local variables into a compiler generated class. This way, it simply needs a bit of compiler trickery to pass around an instance of the compiler generated class, so each time we invoke the delegate we are actually calling the method on this class.

因此本质上,一个封闭变量存储为匿名类的成员变量,该匿名类还包含代表 lambda 表达式或其他封闭变量的代码的委托(delegate)。

如果是这样,当一个方法包含两个不同的 lambda 表达式并且它们都引用同一个局部变量时会发生什么?

void Test(IList list)
{
int i = 0;

list.Any( a => { Console.WriteLine("Lambda one says: {0}", i++); return true;} )
.Any( a => { Console.WriteLine("Lambda two says: {0}", i++); return true;} );

}

我很确定我知道这里的行为。我的问题是,i 到底存储在哪里?

最佳答案

该方法只有一个闭包类,而不是每个匿名方法一个。 一个 类将有两个实例方法和一个字段。该字段将存储i的值,这两个方法将分别对应您的两个匿名方法。

关于c# - 当一个变量被关闭两次时,它存储在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42258450/

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