加载顺序_面试须知(6):C#静态变量与构造函数的加载顺序

63a774fbda912037a66f8e3b5ab89f85.png 9df2525ace8227e79b0613d9440382be.png同学,看一下下面的代码会输出什么?

 class Program

  {

        static int = getNum();

        int = getNum();

        static int num = 1;

        static int getNum()

        {

            return num;

        }

        static void Main(string[] args)

        {

            Console.WriteLine("i={0}", i);

            Console.WriteLine("j={0}", new Program().j);

            Console.Read();

        }

    }

i=0,j=1 3e3930dad000059c5885320f9579c323.png 9df2525ace8227e79b0613d9440382be.png

为什么呢?

Program加载时要先为里面所有的static变量分配内存,所以首先执行“static int = getNum();”,num此时未赋值所以保持默认值为0。然后执行“static int num = 1;”,num赋值变为1。 3e3930dad000059c5885320f9579c323.png 9df2525ace8227e79b0613d9440382be.png不错!再看下面的代码,会输出什么? class  Program{              static void Main(string[] args)        {            TestStatic t = new TestStatic();            t.Print();            Console.Read();        }} class  TestStatic{    public static int TestValue = InitTestValue();    private static int InitTestValue()   {         if (TestValue == 0){        TestValue = 20;       }        return 30;    }     public TestStatic()    {            if (TestValue == 0) {                TestValue = 5;            }    }     static TestStatic()     {          if (TestValue == 0) {            TestValue = 10;         }    }     public void Print()     {         if (TestValue == 5){            TestValue = 6;        }         Console.WriteLine("TestValue : " + TestValue);    }} TestValue : 30

3e3930dad000059c5885320f9579c323.png

静态变量赋值表达式=>静态构造函数=》构造函数

3e3930dad000059c5885320f9579c323.png

9df2525ace8227e79b0613d9440382be.png

小伙子,不错!有钱图!

●  ●  ●

3e3930dad000059c5885320f9579c323.png

END 92f61de5a9306eca8308cd77fba6cc57.png

a51017ce0c687971066e5911f9f0cf79.gif

文章精选

1、面试须知(1):抽象类与抽象方法

2、面试须知(2):常见类型变量与NULL比较是否有效?

3、面试须知(3):C#委托之Func与Action

4、面试须知(4):C# async/awit输出顺序

5、面试须知(5):数据库访问接口ADO.NET

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值