简体   繁体   English

派生类的静态初始化

[英]Static initialization of a derived class

The output of the following program is 以下程序的输出是

base init
BaseMethod
derived init
DerivedMethod

Eg, the call to the base method from the derived class triggers the Base class's init stub and not the same of the Derived class. 例如,从派生类对b​​ase方法的调用会触发Base类的init存根,而不是与Derived类相同。

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(Derived.BaseMethod());
        Console.WriteLine(Derived.DerivedMethod());
    }
}

class Base
{
    public static string BaseMethod() { return "BaseMethod"; }
    static bool init = InitClass();
    static bool InitClass()
    {
        Console.WriteLine("base init");
        return true;
    }
}

class Derived : Base
{
    public static string DerivedMethod() { return "DerivedMethod"; }
    static bool init = InitClass();
    static bool InitClass()
    {
        Console.WriteLine("derived init");
        return true;
    }
}

In reality, my base class has no initialization needs, but my derived class does, and I'd like to ensure that it's run before anyone interacts with the class in any way. 实际上,我的基类不需要初始化,但派生类确实需要初始化,并且我想确保在任何人与该类进行任何交互之前,它都可以运行。 Unfortunately, most of the interaction with it is via methods defined in the base class as per the example above. 不幸的是,大多数与它的交互都是通过根据上面的示例在基类中定义的方法进行的。

I can alter the Derived class to hide the BaseMethod as follows: 我可以更改Derived类以隐藏BaseMethod,如下所示:

class Derived : Base
{
    public static new string BaseMethod() { return Base.BaseMethod(); }
    public static string DerivedMethod() { return "DerivedMethod"; }
    static bool init = InitClass();
    static new bool InitClass()
    {
        Console.WriteLine("derived init");
        return true;
    }
}

And this produces the desired result of initializing the derived class on the call to Derived.BaseMethod(), but it isn't very satisfying since it's meaningless 'routing' code that would have to do be done for every public static base method. 这样就产生了在对Derived.BaseMethod()的调用上初始化派生类的预期结果,但是它并不是很令人满意,因为它是对每个公共静态基方法都必须执行的无意义的“路由”代码。

Any suggestions? 有什么建议么?

instead of the derived class using static new bool InitClass() , why not use a standard static constructor? 而不是使用static new bool InitClass()派生类,为什么不使用标准静态构造函数?

  static bool init = false;

  static Derived()
    {
        Console.WriteLine("derived init");
        init = true;
    }

See C# Static Constructor 请参见C#静态构造函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM