C# 类加载顺序

2023-12-20 13:02:29

TestChidren testChidren = new TestChidren();

1、测试代码

abstract class TestParant
{
    public string Name
    {
        get;
        set;
    } = "1";

    public static string staName
    {
        get;
        set;
    } = "1";

    static TestParant()
    {
        Log.LogManage.Debug($"static TestParant初始化");
    }

    public TestParant()
    {
        Log.LogManage.Debug($"TestParant初始化");
    }
}

class TestChidren : TestParant
{
    public string cName
    {
        get;
        set;
    } = "2";

    public static string cStaName
    {
        get;
        set;
    } = "2";

    public TestChidren()
    {
        Log.LogManage.Debug($"TestChidren初始化");
    }

    static TestChidren()
    {
        Log.LogManage.Debug($"static TestChidren");
    }
}

2、运行结果

2023-12-20 10:41:23,775 
 ->static TestChidren
2023-12-20 10:41:23,780 
 ->static TestParant初始化
2023-12-20 10:41:23,780 
 ->TestParant初始化
2023-12-20 10:41:23,780 
 ->TestChidren初始化

3、加上参数

abstract class TestParant
{
    public string Name
    {
        get;
        set;
    } = "1";

    public static string staName
    {
        get;
        set;
    } = "1";

    static TestParant()
    {
        Log.LogManage.Debug($"static TestParant初始化,staName={staName}");
    }

    public TestParant()
    {
        Log.LogManage.Debug($"TestParant初始化,name={Name}");
    }
}

class TestChidren : TestParant
{
    public string cName
    {
        get;
        set;
    } = "2";

    public static string cStaName
    {
        get;
        set;
    } = "2";

    public TestChidren()
    {
        Log.LogManage.Debug($"TestChidren初始化,cName={cName}");
        Log.LogManage.Debug($"TestChidren初始化,Name={Name}");
    }

    static TestChidren()
    {
        Log.LogManage.Debug($"static TestChidren初始化,cStaName={cStaName}");
        Log.LogManage.Debug($"static TestChidren初始化,staName={staName}");
    }
}

4、结果

2023-12-20 10:51:45,482 
 ->static TestChidren初始化,cStaName=2
2023-12-20 10:51:45,487 
 ->static TestParant初始化,staName=1
2023-12-20 10:51:45,487 
 ->static TestChidren初始化,staName=1
2023-12-20 10:51:45,488 
 ->TestParant初始化,name=1
2023-12-20 10:51:45,488 
 ->TestChidren初始化,cName=2
2023-12-20 10:51:45,488 
 ->TestChidren初始化,Name=1

5、结论

静态部分:先子后父,使用到父类可先初始化父

非静态部分:先父后子

文章来源:https://blog.csdn.net/qq_40934195/article/details/135102499
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。