2011New_C#_深入剖析静态变量 面试题

 

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        class staticclass
        {
            static int count;
            int number;
            public staticclass()
            {
                count = count + 1;
                number = count;
            }
            public void show()
            {
                int i = number;
                int m = count;
            }
        }
        static void Main(string[] args)
        {
            staticclass a = new staticclass();
            a.show();
            staticclass b = new staticclass();
            a.show();
            b.show();
            staticclass c = new staticclass();
            a.show();
            b.show();
            c.show();
        }
    }
}

答案是;

1,1

1,2

2,2

1,3

2,3

3,3

为什么 自己 去琢磨吧

经过N个月的探索,终于研究明白了,现在详细分析一下:

首先我们要从堆栈入手:静态变量每一次进行实例化时候都不再进行重新分配空间,而动态变量却每一次实例化时候另外开辟一个新的空间,原来的空间依然保留,直到GC将它在内存中删除。

我们来对上例进行分析:

首先 count   为静态的,number为动态的

当第一次实行            staticclass a = new staticclass(); 进行实例化,运行构造函数后

count, number的内存如下图:

当第二次进行实例化时候,由于count为静态变量,所以在此实例化后执行构造函数后其count值在原来基础上+1变成为2,原来的1所占用的内存消除。而动态变量并不消除原来内存,而是另外开辟一个新的为新实例化后的b.Number。此时b.number经过构造函数后为2。 而此时第一次构造后的a.number值依然保留 为1如下图:

第三次实例化也是如此,对第一,第二次实例化的number值进行保留,而对count消除原来值,在原来内存上赋予新值。如下图。

当调用a.show时,就去找a.count,a.number ,

b.show 时,就去找b.count,b.number

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值