C# - 基类中的调用方法

Bra*_*don 3 .net c# polymorphism inheritance .net-4.0

我有2个班:

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"); }
}
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我执行以下操作:

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'
Run Code Online (Sandbox Code Playgroud)

我认为这会因多态性而起作用.

但是,它总是每次写入'B输出'.反正有没有让我按照我想要的方式工作?

编辑修复代码示例.

Dus*_*vis 5

当你使用NEW从基类"隐藏"一个方法时,你只是隐藏它,就是这样.当您明确调用基类实现时,它仍然会被调用.

不包含WriteLine,因此您需要修复它.当我修好它时,我得到了

Output from B
Output


namespace ConsoleApplication11
{
    class Program
    {
        static void Main(string[] args)
        {
            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' 
            Console.ReadKey();
        }
    }

    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"); }
    }
}
Run Code Online (Sandbox Code Playgroud)