• c#构造初使化的顺序


    这个很基础的知识,但我至今才意识到它。想想也很失败。

    直接上代码:很简单

    public class Base
        {
            int i=0;
    
            public Base()
            {
                System.Console.WriteLine("我是基类构造器");
            }
            
        }
    
     class Program
        {
            static void Main(string[] args)
            {
                Base d = new Base();
            }
        }

     对于上面的代码。是先执行构造器,还是先初使化字段 i 变量呢?其实只要意识到这个问题,也就很容易试出来,它应当是先初使化字段 i 变量。

    那么现在如果Base 派生出一个子类,那它的构造顺序又是怎么样的呢?

     /// <summary>
        /// 基类
        /// </summary>
        public class Base
        {
           public int baseint = 100;
            public Base()
            {
                System.Console.WriteLine("构造器:我是基类构造器");
               
            }
    
            private class Inner
            {
                public Inner()
                {
                    System.Console.WriteLine("字段:我是基类Inner");
                }
            }
    
            /// <summary>
            /// 字段初使化
            /// </summary>
            private Inner inner = new Inner();
        }
    
    
       /// <summary>
       /// 子类
       /// </summary>
        class Derived : Base
        {
           
    
            public Derived()
            {
                System.Console.WriteLine("构造器:我是子类构造器");
                
            }
    
    
           private class Inner
            {
                public Inner()
                {
                    System.Console.WriteLine("字段:我是子类Inner");
                }
            }
    
            /// <summary>
            /// 字段初使化
            /// </summary>
            private Inner inner = new Inner();
    
        }

    所以说它的执行顺序为:子类字段-父类字段-父类构造器-子类构造器

  • 相关阅读:
    SPOJ1043 GSS1(线段树)
    cf1028C. Rectangles(前缀和)
    cf559C. Gerald and Giant Chess(容斥原理)
    五校联考解题报告
    BZOJ1853: [Scoi2010]幸运数字(容斥原理)
    使用spring-amqp结合使用rabbitmq
    instanceof关键字
    qml学习:对象和属性
    [置顶] 推荐12款很棒的HTML5开发框架和开发工具
    linux系统开机过程描述
  • 原文地址:https://www.cnblogs.com/qgf522/p/3277482.html
Copyright © 2020-2023  润新知