C#覆盖静态方法

时间:2019-03-21 18:43:00

标签: c# methods override

我有以下类和方法

public class X
{
    public static void M1(...)
    {
        ...
        var isSomething = M2(...);
        ...
    }

    public static bool M2(...) { ... }
}

我需要实现一个具有相同签名的新M2方法,以便在某些情况下调用它。 为此,我正在考虑实现一个扩展X并覆盖M2方法的新类Y,因此,当我调用Y.M1()时,我想使用y.M2()。

public class Y : X
{
    public static [override] bool M2(...) { ... }
}

但是静态方法不能被覆盖。 任何人都有建议我该怎么做?

2 个答案:

答案 0 :(得分:2)

静态方法不能被覆盖。 Dynamic binding仅适用于对象实例。

您可以使用new关键字“隐藏”基类中的静态方法,如here所述。您可以使用以下样式编写Y.M2():

public class Y : X
{
    public static new bool M2(...) { ... }
}

请记住,此样式与 normal 虚拟非静态方法覆盖不同。使用非静态方法重写时,方法绑定将在运行时根据实际对象类型完成。静态方法绑定是在编译时完成的。

答案 1 :(得分:1)

尚不清楚您要做什么,但是据我了解您的问题,您想通过其他方式更改M1()的行为,该行为由类Y继承静态方法M2()。如果涉及的所有方法都是静态的,则这是不可能的,但是如果将M1()声明为非静态的,则可以产生所需的效果。这可以通过以下方式完成:

public class X
    {
    public Boolean M1 (Int32 x1)
        {
        return M2 (x1);
        }
    public virtual Boolean M2 (Int32 x2)
        {
        return M3 (x2);
        }
    public static Boolean M3 (Int32 x2)
        {
        return x2 >= 0;
        }
    }

public class Y : X
    {
    public override Boolean M2 (Int32 x2)
        {
        return M3 (x2);
        }
    public static new Boolean M3 (Int32 x2)
        {
        return x2 < 0;
        }
    }

这是一个测试用例:

Boolean fTest1 = new X ().M1 (1);
Boolean fTest2 = new Y ().M1 (1);

Console.Write ("{0} {1}", fTest1, fTest2);

这将输出:

True False

因此,在M2()中调用静态方法M3()的包装器方法Xvirtual,并且可以在Y中重写,从而调用其他静态方法方法M3()。因此,如果您使用派生类Y的实例,则在继承的方法M2()中对M1()的调用将定向到{{ 1}},它依次调用另一个M2(),并具有所需的行为更改-在此示例中,结果是布尔值的倒数。