关于继承

时间:2016-06-03 05:20:35

标签: c# inheritance

为什么这段代码产生输出“Base class”而不是“Derived2 class”?

namespace TestConsoleApplication
{ 
    class Baseclass
    { 
        public void fun()
        { 
            Console.Write("Base class" + " ");
        } 
    } 
    class Derived1: Baseclass
    { 
        new void fun()
        {
            Console.Write("Derived1 class" + " "); 
        } 
    } 
    class Derived2: Derived1
    { 
        new void fun()
        { 
            Console.Write("Derived2 class" + " ");
        }
    }
    class Program
    { 
        public static void Main(string[ ] args)
        { 
            Derived2 d = new Derived2(); 
            d.fun(); 
        } 
    } 
}

1 个答案:

答案 0 :(得分:4)

因为您没有将该方法声明为公开。

您告诉它隐藏原始定义,而不是覆盖它 - 将执行,但默认访问修饰符是私有,而非公开

例如,从Derived2

中调用方法时
class Derived2 : Derived1
{
    new void fun()
    {
        Console.Write("Derived2 class" + " ");
    }

    public void Test()
    {
        fun();
    }
}
class Program
{
    public static void Main(string[] args)
    {
        Derived2 d = new Derived2();
        d.Test(); //Prints 'Derived2 class'
    }
}

将其设置为公开,确实会在原始示例中打印Derived2

public new void fun()
{
    Console.Write("Derived2 class" + " ");
}