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)
那么该类将不会被实例化