在C#的嵌套函数中分配的捕获变量在哪里 [英] Where is the captured variables allocated in nested function in C#

查看:79
本文介绍了在C#的嵌套函数中分配的捕获变量在哪里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提到的嵌套函数意味着它既可以是lambda函数,也可以是局部函数.

The nested function mentioned means it could be both lambda function and local function.

我很好奇捕获变量的分配位置.

I am curious about where the captured variables are allocated.

例如:

private Func<int> Test(int arg)
{
    var x = arg;
    return () => x;
}

本地变量 x 由返回的lambda函数捕获.

The local variable x is captured by the lambda function returned.

然后,该 x 在内存中的分配位置是什么?是在堆栈还是堆内存上?

Then where is this x allocated in memory? Is it on stack or heap memory?

如果此 x 在堆栈中,则在 Test 上进行的任何进一步调用都可能会更改 x 的值,并返回lambda函数的行为可能会被错误地修改.

If this x is on stack, any further call on Test could change the value of x and the behavior of the lambda function returned could be incorrectly modified.

但是如果 是动态分配在堆内存中的,它将不再像局部变量一样.

But if it is dynamically allocated on heap memory, it would not be like a local variable any more.

它是否首先在堆栈中分配并在 Test 返回时立即转移到堆?(我想不是因为这听起来好像不必要地花费了一些资源,而是在 Test 返回后使其可用于访问此 x 的工作原理?)

Was it first allocated in stack and transferred to heap right on Test returns? (I guess not because it sounds like unnecessarily costing some resources, but how does it work to make it available to access this x after Test returns?)

推荐答案

在这里,堆栈vs堆不是一个非常有用的区别,但是我可以告诉您发生了什么.编译器在后台重新编写该代码.它将一个类添加到项目中,该类具有一个整数值作为成员.然后,此函数和lambda函数都获得对该新类的相同实例的引用.

Stack vs heap isn't a very useful distinction here, but I can give you an idea of what happens. The compiler re-writes this code behind the scenes. It adds a class to the project which has an integer value as a member. Then both this function and the lambda function get a reference to the same instance of this new class.

至少,这是我上次阅读它时所采用的方式,这是在一段时间之前被承认的……但是我怀疑它的变化很大.欢迎使用编程,这里您认为所知道的一切实际上都是过去一段时间内情况的快照.

At least, that's how this was handled the last time I read about it, which was admittedly some time ago now... but I doubt it's changed much. Welcome to programming, where everything you think you know is really a snapshot of how things were at some time in the past.

这篇关于在C#的嵌套函数中分配的捕获变量在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆