zoukankan      html  css  js  c++  java
  • C#-------------类型构造器

        class Foo
        {
            public static string Field = GetString("Initialize the static field!");
            public static string GetString(string s)
            {
                Console.WriteLine(s);
                return s;
            }
        }

    执行代码:

            static void Main(string[] args)
            {
                Console.WriteLine("Start.....");
                Foo.GetString("Manually invoke the static GetString() Method!");
                Console.Read();
            }

    运行结果:

    有的人肯定想这个是理所当然的,因为一般的执行过程如下:

      1.静态字段

      2.静态构造函数

      3.实例字段

      4.实例构造函数

    但如果我们稍微的修改一下代码呢!!!

            static void Main(string[] args)
            {
                Console.WriteLine("Start.....");
                Foo.GetString("Manually invoke the static GetString() Method!");
                var d = Foo.Field;
                Console.Read();
            }

    这个你知道是为什么吗?

      要解释这个,我们还需要知道类型构造器(.cctor)

      我们将从源代码解析!!!!

      

    我们可以看到在这个类的声明上面多了一个beforefieldinit 关键字,表明在任何时候都可以执行构造器

      如果我们想让代码向最开始一样执行,那么我们只需要加上一个静态构造函数

        class Program
        {
            /*
             类型构成器的两种形式:
             *  1.precise(有显示的声明构造函数)
             *  2.beforefieldinit  d8hkt1yJm95NtWBdPjwh
             */
            static void Main(string[] args)
            {
                Console.WriteLine("Start.....");
                Foo.GetString("Manually invoke the static GetString() Method!");
                var d = Foo.Field;
                Console.Read();
            }
        }
        class Foo
        {
            static Foo()
            {
    
            }
            public static string Field = GetString("Initialize the static field!");
            public static string GetString(string s)
            {
                Console.WriteLine(s);
                return s;
            }
        }

      因为加了静态的构造函数,程序的运行就会向原来的那样执行

    Hold on, everything is possible.
  • 相关阅读:
    LeetCode Arithmetic Slices
    LeetCode Number of Longest Increasing Subsequence
    LeetCode Longest Increasing Subsequence
    shrio注解的方式进行权限控制
    30分钟学会如何使用Shiro(转自:http://www.cnblogs.com/learnhow/p/5694876.html)
    eclipse逆向生成实体类
    redis2.3.7安装时出现undefined reference to `clock_gettime'
    使用Nginx+Lua(OpenResty)开发高性能Web应用
    shrio初体验(2)Realm
    shrio初体验(1)
  • 原文地址:https://www.cnblogs.com/student-note/p/6823817.html
Copyright © 2011-2022 走看看