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

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

问题描述

正如你可以在下面的代码中看到的,DoStuff()方法是在构造一个Child对象之前在Init()之前调用的。

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.

在我有许多儿童阶级的情况下。因此,在每个孩子的构造函数中直接在Init()之后重复调用DoStuff()方法不会是一个优雅的解决方案。

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.

可以在父类中创建某种类型的后构造函数,它将在子构造函数之后执行?这样,我可以调用DoStuff()方法在那里。

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
    }
}


推荐答案

如何实现:

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#如何在对象构建之后执行代码(postconstruction)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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