C#小知识之有趣的类型静态构造器

前端技术 2023/09/02 C#

这是C#中一个有趣的现象,也许您从中可以窥见些许CLR在构造类型时的行为,以及JIT编译的触发式编译过程。

看下面一段代码:

复制代码 代码如下:

class Program
    {
        static void Main()
        {
            myValueType1 type1 = new myValueType1();
            Console.WriteLine(myValueType1.myInt);
            Console.WriteLine(\"**********************\");
            myValueType2 type2 = new myValueType2();
            type2.myInt =23;
            Console.WriteLine(type2.myInt);
            Console.WriteLine(\"**********************\");
            myValueType3 type3 = new myValueType3();
        }
    }

    struct myValueType1
    {
        static myValueType1()
        {
            Console.WriteLine(\"Hello from myValueType1\");
           // myInt = 111;
        }
        public static Int32 myInt;
    }

    struct myValueType2
    {
        static myValueType2()
        {
            Console.WriteLine(\"Hello from myValueType2\");
        }
        public Int32 myInt;
    }

    struct myValueType3
    {
        static myValueType3()
        {
            Console.WriteLine(\"Hello from myValueType3\");
            myInt = 333;
        }
        public static Int32 myInt;
    }

本文地址:https://www.stayed.cn/item/5891

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。