C#如何在对象构建后执行代码(后构建) [英] C# How to execute code after object construction (postconstruction)

查看:24
本文介绍了C#如何在对象构建后执行代码(后构建)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如您在下面的代码中所见,在构造 Child 对象期间,DoStuff() 方法在 Init() 方法之前被调用.>

我现在有很多子课程.因此,在每个子节点的构造函数中直接在 Init() 之后重复调用 DoStuff() 方法不是一个优雅的解决方案.

有什么办法可以在父类中创建某种后构造函数,在子类的构造函数之后执行?这样,我就可以调用那里的 DoStuff() 方法.

如果您有任何其他可以解决我的问题的设计理念,我也很想听听!

抽象类父级{公共父(){做东西();}受保护的抽象无效 DoStuff();}班级孩子:父母{公共儿童()//DoStuff 在 Init 之前被调用//因为预构造{在里面();}私有无效初始化(){//需要在做事前调用}受保护的覆盖无效 DoStuff(){//东西}}

解决方案

这个怎么样:

抽象类父级{公共父(){在里面();做东西();}受保护的抽象无效 DoStuff();受保护的抽象无效初始化();}班级孩子:父母{公共儿童(){}受保护的覆盖 void Init(){//需要在做事前调用}受保护的覆盖无效 DoStuff(){//东西}}

As you can see in the code below, the DoStuff() method is getting called before the Init() one during the construction of a Child object.

I'm in a situation where I have numerous child classes. Therefore, repeating a call to the DoStuff() method directly after Init() in the constructor of each child wouldn't be an elegant solution.

Is there any way I could create some kind of post constructor in the parent class that would be executed after the child's constructor? This way, I could call to the DoStuff() method there.

If you have any other design idea which could solve my problem, I'd like to hear it too!

abstract class Parent
{
    public Parent()
    {
        DoStuff();
    }

    protected abstract void DoStuff();
}

class Child : Parent
{
    public Child()
    // DoStuff is called here before Init
    // because of the preconstruction
    {
        Init();
    }

    private void Init()
    {
        // needs to be called before doing stuff
    }

    protected override void DoStuff() 
    {
        // stuff
    }
}

解决方案

How about this:

abstract class Parent
{
    public Parent()
    {
        Init();
        DoStuff();
    }

    protected abstract void DoStuff();
    protected abstract void Init();
}

class Child : Parent
{
    public Child()
    {
    }

    protected override void Init()
    {
        // needs to be called before doing stuff
    }

    protected override void DoStuff() 
    {
        // stuff
    }
}

这篇关于C#如何在对象构建后执行代码(后构建)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆