考虑以下代码:
using System;
public delegate int IntToInt(int n);
public class Foo
{
static int a = 2;
static IntToInt b(int c)
{
int d = a + c;
Console.WriteLine(d);
return delegate(int n) { return c + n; };
}
public static void Main(string[] args)
{
Console.WriteLine(b(3)(4));
}
}
为什么 c
最有可能分配在堆 而不是堆栈?
我读到这是因为 c
具有无限范围。
你能详细解释一下这个术语吗?
最佳答案
Why would
c
most likely be allocated on the heap rather than the stack?
您的示例中的两个c
需要分配 - c
- Foo.b
的参数,和c
-the-capture-of-delegate.
Foo.b
的参数在堆栈上分配,完全符合您的预期。- 另一方面,委托(delegate)的捕获是在堆上分配的,因为
c
的生命周期与委托(delegate)对象的生命周期相关,后者是无限的。
关于c# - 无限范围变量将分配在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51233889/