我们知道委托(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包含对存储字符串的堆内存位置的引用。
现在,
- When we define delegate or instance of delegate, where they (fun_delegate and response) allocate memory, whether on stack or on heap?
- 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/