首页 > 解决方案 > 方法擦除:为什么说派生类的方法隐藏了基类,反之呢?

问题描述

class Animal
{
    public void Foo() { Console.WriteLine("Animal::Foo()"); }
}

class Cat : Animal
{
    public void Foo() { Console.WriteLine("Cat::Foo()"); }
}

class Test
{
    static void Main(string[] args)
    {
        Animal a;

        a = new Cat();
        a.Foo();  // output --> "Animal::Foo()"
    }
}

编译器警告说:

Cat.Foo 隐藏了继承的成员

然而,输出实际上来自基类。所以对我来说,似乎反过来,我调用的那个被基类中的那个隐藏了。

标签: c#oopmember-hiding

解决方案


你的程序的输出是Animal类的实现,Foo因为引用的类型是Animal和非Cat

如果引用的类型为Cat,则输出为"Cat::Foo()".

类的Foo方法Cat隐藏了类的Foo方法,Animal因为基类不能也不应该知道它们的派生类,而派生类是并且必须知道它们的基类。

要故意隐藏基类的成员,请使用new修饰符。这将告诉编译器隐藏是故意的,并将抑制警告。


推荐阅读