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

标签 c# delegates

考虑以下代码:

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/

相关文章:

c# - 更新字段时违反了 UNIQUE KEY 约束

c# - 对象类型的转换

c# - 函数引用与 Action<T> 有何不同

ios - 在 UIView/UIViewController 关系中定义委托(delegate)

c# - 如何找出产生 XamlParseException 的 XAML 文件

c# - 如何在 asp.net 中使用 chekboxchanged 之前的确认?

c# - 使用 C# 在 MySQL 中使用 Select 和 Where 参数 = any\dontcare

ios - 在 Swift 扩展中存储变量的替代方法

C#:委托(delegate),紧凑访问者, "universal callable"参数类型

c# - 无法从委托(delegate)对象调用列表中正确删除方法