gpt4 book ai didi

c# - 无限范围变量将分配在哪里?

转载 作者:太空宇宙 更新时间:2023-11-03 20:55:14 25 4
gpt4 key购买 nike

考虑以下代码:

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/

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