当前位置:编程学习 > asp >>

关于静态变量,静态构造函数,实例变量,构造函数的执行.

 

请看下面的代码,其实输入结果如下:

 

第一个输出和第二个输出都比较理解,第三个输出是为何(为什么所有静态变量和静态构造函数都没有执行)?

 

大家来讨论一下!

 

\ 

 

static void Main(string[] args)

        {

                        Console.WriteLine("BaseA basea = new BaseA();");

            BaseA basea = new BaseA();

            basea.MyFun();

            Console.WriteLine();

 

            Console.WriteLine("BaseB baseb = new BaseB();");

            BaseB baseb = new BaseB();

            baseb.MyFun();

            Console.WriteLine();

 

            Console.WriteLine("BaseA basec = new BaseB();");

            BaseA basec = new BaseB();

            basec.MyFun();

            Console.WriteLine();

}

 

 

        public class BaseA

        {

            public static MyTest a1 = new MyTest("基类静态变量");

            public MyTest a2 = new MyTest("基类实例变量");

            static BaseA()

            {

                MyTest a3 = new MyTest("基类静态构造函数");

            }

            public BaseA()

            {

                MyTest a4 = new MyTest("基类实例构造函数");

            }

            public virtual void MyFun()

            {

                MyTest a5 = new MyTest("基类实例函数MyFun");

            }

        }

        public class BaseB : BaseA

        {

            public static MyTest b1 = new MyTest("派生静态变量");

            public MyTest b2 = new MyTest("派生实例变量");

            static BaseB()

            {

                MyTest b3 = new MyTest("派生静态构造函数");

            }

            public BaseB()

            {

                MyTest b4 = new MyTest("派生实例构造函数");

            }

            public new void MyFun()

            {

                MyTest b5 = new MyTest("派生实例函数MyFun");

            }

        }

        public class MyTest

        {

            public MyTest(string info)

            {

                Console.WriteLine(info);

            }

        }

 

作者 taoliuhua

补充:Web开发 , ASP.Net ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,