C# 类加载顺序

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、结论

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

非静态部分:先父后子

  • 4
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值