繁体   English   中英

派生类的静态初始化

[英]Static initialization of a derived class

以下程序的输出是

base init
BaseMethod
derived init
DerivedMethod

例如,从派生类对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;
    }
}

实际上,我的基类不需要初始化,但派生类确实需要初始化,并且我想确保在任何人与该类进行任何交互之前,它都可以运行。 不幸的是,大多数与它的交互都是通过根据上面的示例在基类中定义的方法进行的。

我可以更改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;
    }
}

这样就产生了在对Derived.BaseMethod()的调用上初始化派生类的预期结果,但是它并不是很令人满意,因为它是对每个公共静态基方法都必须执行的无意义的“路由”代码。

有什么建议么?

而不是使用static new bool InitClass()派生类,为什么不使用标准静态构造函数?

  static bool init = false;

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

请参见C#静态构造函数

暂无
暂无

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

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