我有以下类和方法
public class X
{
public static void M1(...)
{
...
var isSomething = M2(...);
...
}
public static bool M2(...) { ... }
}
我需要实现一个具有相同签名的新M2方法,以便在某些情况下调用。为此,我想实现一个新的类Y扩展X并覆盖M2方法,所以当我调用Y.M1()时,我想使用y.M2()。
public class Y : X
{
public static [override] bool M2(...) { ... }
}
但静态方法无法覆盖。任何人都有建议我怎么能这样做?
目前还不完全清楚你要做什么,但据我理解你的问题,你想通过一个不同的静态方法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()
中调用静态方法X
的包装器方法virtual
是Y
,可以在M3()
中重写,调用不同的静态方法Y
。因此,如果您正在使用派生类M2()
的实例,则在继承的方法M1()
中对M2()
的调用将被引导到Y
内部覆盖的M3()
方法,而Dynamic binding又调用其他new
,具有所需的行为更改 - 在在这个例子中,结果是反布尔值。
静态方法无法覆盖。 here只能用于对象实例。
您可以使用public class Y : X
{
public static new bool M2(...) { ... }
}
关键字从基类“隐藏”静态方法,如qazxswpoi所述。在您的情况下,您可以使用以下样式编写Y.M2():
qazxswpoi
请记住,此样式与普通虚拟非静态方法覆盖不同。使用非静态方法覆盖,方法绑定根据实际对象类型在运行时完成。静态方法绑定在编译时完成。