调用构造函数库执行代码后 [英] Call Constructor Base after Code Execution

查看:98
本文介绍了调用构造函数库执行代码后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我们有A类和B类ClassB的扩展A类(ClassB的:ClassA的)

Let say we have Class A and Class B. ClassB extends Class A. (ClassB : ClassA)

现在让我们说,每当我实例ClassB的,我会。喜欢跑步一些随机代码,然后才称之为基地达到ClassA的构造函数

Now let's say that whenever I instantiate ClassB, I'd like to Run some Random code and only then call "base" to reach ClassA constructor.

我爱:

class ClassA
{
    public ClassA()
    {
        Console.WriteLine("Initialization");
    }  
}

class ClassB : ClassA
{
    public ClassB() //: base() 
    {
        // Using :base() as commented above, I would execute ClassA ctor before                                                         //          Console.WriteLine as it is below this line... 
        Console.WriteLine("Before new");
        //base() //Calls ClassA constructor using inheritance
        //Run some more Codes here...
    }
}

在编程语言我平时一起工作,我能做到这一点,通过简单地调用超级()Console.WriteLine()后;但我不能让它在C#。是否有任何其他的语法或其他方式来做到这一点?

In the programming language I usually work with, I can do that, by simply calling "super()" after Console.WriteLine(); But I cant make it in C#. Is there any other syntax or other way to do that?

谢谢!

推荐答案

有一个使用的实例变量初始化做的哈克方式:

There's a hacky way of doing it using an instance variable initializer:

using System;

class ClassA
{
    public ClassA()
    {
        Console.WriteLine("Initialization");
    }  
}

class ClassB : ClassA
{
    private readonly int ignoreMe = BeforeBaseConstructorCall();

    public ClassB()
    {
    }

    private static int BeforeBaseConstructorCall()
    {
        Console.WriteLine("Before new");
        return 0; // We really don't care
    }
}

class Test
{
    static void Main()
    {
        new ClassB();
    }    
}



的哈克方式做的是重新思考如何构建一个 ClassB的开始。而不是让客户直接调用构造函数,提供了一个静态方法为他们呼吁:

The less hacky way of doing it is to rethink how you construct a ClassB to start with. Instead of having clients call the constructor directly, provide a static method for them to call:

public static ClassB CreateInstance()
{
    Console.WriteLine("Before initialization stuff");
    return new ClassB();
}

这篇关于调用构造函数库执行代码后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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