• c#类的初始化顺序


    本文转载:http://www.cnblogs.com/ybhcolin/archive/2010/09/24/1834219.html

    类在初始化时的执行顺序,依次如下:

    1: 子类静态变量

    2: 子类静态构造函数

    3: 子类非静态变量

    4: 父类静态变量

    5: 父类静态构造函数

    6: 父类非静态变量

    7: 父类构造函数

    8: 子类构造函数

    对于静态变量与静态构造函数而言, 无论对一个类创建多少个实例,它的静态成员都只有一个副本。 也就是说,静态变量与静态构造函数只初始化一次(在类第一次实例化时)

    以下代码: 

    复制代码
     1  class Class1
     2     {
     3         public static int Count = 0;
     4         static Class1()
     5         {
     6             Count++;
     7         }
     8         public Class1()
     9         {
    10             Count++;
    11         }
    12     }
    复制代码

    实例化代码:

    1 Class1 c = new Class1();
    2 Class1 cc = new Class1();
    3 Console.WriteLine(Class1.Count.ToString());
    4 Console.Read();

    当弟一次实例化时, Count值变成2,  当第二次实例化时, 则不会执行静态构造函数与静态变量.  此时Count的值变成3.   所以,最后结果Count值为3

     public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                TestClass ts1 = new TestClass();
            }
        }
    
        public class TestClass : TestBase
        {
            private string str = ""; //3: 子类非静态变量
            public static string str1 = "";//1: 子类静态变量
    
            static TestClass() //2: 子类静态构造函数
            {
     
            }   
            public TestClass()//8: 子类构造函数
            {
     
            }
    
        }
    
        public class TestBase
        {
            public string test = "";//6: 父类非静态变量
            public static string test1 = "";//4: 父类静态变量
    
            static TestBase() //5: 父类静态构造函数
            {
     
            }
    
            public TestBase()//7: 父类构造函数
            {
     
            }
        }
    View Code
  • 相关阅读:
    Leetcode Binary Tree Paths
    Leetcode Lowest Common Ancestor of a Binary Tree
    Leetcode Lowest Common Ancestor of a Binary Search Tree
    Leetcode Path Sum
    Leetcode Symmetric Tree
    Leetcode Invert Binary Tree
    Leetcode Same Tree
    Leetcode Maximum Depth of Binary Tree
    Python Json&Pickle&模块
    Python Shelve模块
  • 原文地址:https://www.cnblogs.com/51net/p/3887175.html
Copyright © 2020-2023  润新知