zoukankan      html  css  js  c++  java
  • C#的类成员初始化顺序

    C#的类成员的定义和声明如下

    
    
    using UnityEngine;
    using System.Collections;
    
    
    public class TestController : ECController {
         
    
    
    int a = b();
    public static int test=10;
    static int g = gg();
    public static TestController Instance = new TestController();
    
    static int gg()
    {
    Debug.Log("~~~~~~~gg~~~~");
    return 99;
    }
    
    static int d=100;
    static int b()
    {
    Debug.Log("~~~~~~~b~~~~~~~");
    test=test+2;
    return test;
    }
    
    int c=9;
    private TestController()
    {
    ControllerManager.Instance.AddListener(this);
    Debug.Log("~~~TestController~test~~~~~~~"+test+" "+c+" d "+d);
    test=9;
    }
    static TestController()
    {
    Debug.Log("~~~TestController~test~~~~~~~"+test+" d "+d+" f "+f);
    
    }
    static int f=100;
    
    	
    	static void main()
    	{
    
             bool flag=false;
                   if(flag)//if(false)
             {
              
             }
                   Debug.Log("~~~main~~");
    		TestController t = TestController.Instance;
              Debug.Log("~~~~~main~2~~"+TestController.f);
    
    
    
    	}
    	
    
    }
    

      

     输出的结果:


    ~~~~~~~gg~~~~
    ~~~~~~~b~~~~~~~

    ~~~TestController~test~~~~~~~12   9  d  0

    ~~static~TestController~test~~~~~~~9  d  100  f 100

    ~~~main~~
    ~~~main~2~~100

    说明总结:

    当C#的类被确定可能会实例化时, 类的构造函数才被调用:

    即C#会先预先运行一次,但不初始化非静态或常态变量,此时,如果该类可能被运行时,

    该类就会被实例化,此时所有操作都是在main函数开始之前!

    当该类实例化时 首先是 

    Instance之前的静态成员按照顺序依据赋值初始化

    然后是所有的非静态成员初始化

    最后是Instance之后的静态成员依据赋值初始化

    最最后 开始运行,即执行main()

    如果把main中的if(flag) 换为 if(false)

    那么该类将不会被实例化 

  • 相关阅读:
    (转)mysql 中的 latch锁和Tlock(事务锁), DML加锁规则,以及死锁分析
    改变主库sync_binlog,减小主从同步延时
    windows10上使用SourceInsight阅读mysql源码
    centos6.5安装systemstap
    centos6.5编译调试mysql-5.7.18
    事物特性
    Union和union all区别?
    Join(inner、left、right)的区别?
    hashhashmaphashTablehashSet
    String、StringBuffer、StringBuilder区别
  • 原文地址:https://www.cnblogs.com/lydyy/p/5442915.html
Copyright © 2011-2022 走看看