欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

c#構(gòu)造初始化的順序淺析

 更新時(shí)間:2013年08月23日 15:17:39   作者:  
這篇文章介紹了c#構(gòu)造初始化的順序,有需要的朋友可以參考一下

這個(gè)很基礎(chǔ)的知識(shí),但我至今才意識(shí)到它。想想也很失敗。

直接上代碼:很簡(jiǎn)單

復(fù)制代碼 代碼如下:

public class Base
    {
        int i=0;

        public Base()
        {
            System.Console.WriteLine("我是基類構(gòu)造器");
        }

    }

 class Program
    {
        static void Main(string[] args)
        {
            Base d = new Base();
        }
    }


對(duì)于上面的代碼。是先執(zhí)行構(gòu)造器,還是先初使化字段 i 變量呢?其實(shí)只要意識(shí)到這個(gè)問(wèn)題,也就很容易試出來(lái),它應(yīng)當(dāng)是先初使化字段 i 變量。

那么現(xiàn)在如果Base 派生出一個(gè)子類,那它的構(gòu)造順序又是怎么樣的呢?

復(fù)制代碼 代碼如下:

/// <summary>
    /// 基類
    /// </summary>
    public class Base
    {
       public int baseint = 100;
        public Base()
        {
            System.Console.WriteLine("構(gòu)造器:我是基類構(gòu)造器");

        }

        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("構(gòu)造器:我是子類構(gòu)造器");

        }


       private class Inner
        {
            public Inner()
            {
                System.Console.WriteLine("字段:我是子類Inner");
            }
        }

        /// <summary>
        /// 字段初使化
        /// </summary>
        private Inner inner = new Inner();

    }


所以說(shuō)它的執(zhí)行順序?yàn)椋鹤宇愖侄危割愖侄危割悩?gòu)造器-子類構(gòu)造器

相關(guān)文章

最新評(píng)論