【问题标题】:Mechanism of memory allocation to delegates in c#.netc#.net中委托的内存分配机制
【发布时间】:2016-10-25 03:36:25
【问题描述】:

我们知道委托是引用类型,指的是函数。

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. 当我们定义委托或委托实例时,它们(fun_delegate 和响应)在哪里分配内存,无论是在堆栈上还是在堆上?
  2. 为什么需要创建委托实例以将其引用到任何函数?

【问题讨论】:

标签: c# .net memory-management reference delegates


【解决方案1】:

当我们定义委托或委托实例时,它们在哪里 (fun_delegate and response) 分配内存,无论是在堆栈上还是在 堆?

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

为什么需要创建一个委托实例来引用它 有什么功能吗?

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2011-02-08
    相关资源
    最近更新 更多