c# - c#.net 中委托(delegate)的内存分配机制

标签 c# .net memory-management reference delegates

我们知道委托(delegate)是引用类型,引用函数。

using System;
namespace Testing_Delegates

{

class Program
{
    delegate void fun_delegate();
    fun_delegate response;

    static void Main(string[] args)
    {
        Program p = new Program();

        p.fun();//Calling function directly
        p.response += p.fun;//Setting reference to the function via delegate
    }

    public void fun()
    {
        int lvariable = 10000;
        string rvariable = "Hello Developers!";
        Console.WriteLine(lvariable + " " + rvariable);
    }
}
}

众所周知,函数(fun)内部的局部变量是lvariable,它在堆栈上分配内存,rvariable包含对存储字符串的堆内存位置的引用。

现在,

  1. When we define delegate or instance of delegate, where they (fun_delegate and response) allocate memory, whether on stack or on heap?
  2. Why there is need to create an instance of delegate to reference it to any function?

最佳答案

When we define delegate or instance of delegate, where they (fun_delegate and response) allocate memory, whether on stack or on heap?

您的示例中的

fun_delegate 是一个类,并且存储在元数据中。 response 是引用类型中的一个字段,与该类型的所有其他字段一起分配在堆上。

Why there is need to create an instance of delegate to reference it to any function?

我们需要创建一个实例来分配内存中的位置来存储数据。除非您为字段/变量分配内存,否则没有地方可以存储它们的值。

关于c# - c#.net 中委托(delegate)的内存分配机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37980819/

相关文章:

c - 虚拟地址到物理地址的段错误

c# - 表 __MigrationHistory 未更新

c# - 如何创建可插入的 ASP.Net 网站?

c# - 如何将WPF英寸单位转换为Winforms像素,反之亦然?

c# - 将应用程序依赖项部署到程序文件夹或 GAC

c++ - 在 C++ 中返回对象

iphone - 在 didReceiveMemoryWarning 之后我应该用什么方法重新创建资源?

c# - 引发自定义事件以允许 Web 用户控件相互通信

c# - 有没有更简单的方法来处理单元测试条件太多的方法?

.net - 如何确定当前应用程序是否为 ASP.NET Web 应用程序