我有两个类:
public class A
{
public void WriteLine(string toWrite) { Console.WriteLine(toWrite); }
}
public class B : A
{
public new void WriteLine(string toWrite) { Console.WriteLine(toWrite + " from B"); }
}
在我的代码中,我执行以下操作:
B writeClass = new B();
writeClass.WriteLine("Output"); // I expect to see 'Output from B'
A otherClass = (A)writeClass;
otherClass.WriteLine("Output"); // I expect to see just 'Output'
我原以为这会起作用,因为涉及到多态性。
然而,每次都会输出“从B输出的结果”。有没有办法让它按照我想要的方式工作?
编辑 修复代码示例。
public void WriteLine
而不是public void Write
。 - Rami AlshareefA
中的方法应该是WriteLine
而不是Write
吗? - Russ CamB的输出
- StriplingWarrior