欢迎您访问新疆栾骏商贸有限公司,公司主营电子五金轴承产品批发业务!
全国咨询热线: 400-8878-609

新闻资讯

常见问题

c#栈变化规则图解示例(栈的生长与消亡)

作者:用户投稿2026-01-11 15:44:22

栈的变化规则:

1、方法调用会导致栈的生长,具体包括两个步骤:一、插入方法返回地址(下图中的Fn:);二、将实际参数按值(可以使用ref或out修饰)拷贝并插入到栈中(可以使用虚参数访问)。
2、遇到局部变量定义会向栈中插入局部变量。
3、遇到return语句会导致栈消亡,一直消亡到方法返回地址,并把return的返回值设置到方法返回地址中。
4、这里先不考虑中括号导致的栈的消亡。



复制代码 代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StackAndHeapStudy
{
    unsafe class Program
    {
        static void Main(string[] args)
        {
            var test = new TestClass();
            SetX(test);
            Console.WriteLine(*test.X);
            Console.WriteLine(*test.X);
        }

        private static void SetX(TestClass test)
        {
            var X = 10;

            test.X = &X;
        }
    }

    unsafe class TestClass
    {
        public int* X;
    }
}