如何在Derived 1和Derived 2中访问结果,而不是基类

时间:2016-12-05 02:57:15

标签: c# inheritance overloading

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();

        Derived1 e = new Derived1();
        d.fun();
        e.fun();
    }
}

如何在Derived 1和Derived 2中访问结果,而不是基类 这是超载还是超载?

1 个答案:

答案 0 :(得分:0)

new既不会超载也不会覆盖。它主要是说'当我被调用时,并且对象被转换为Derived1 ,然后调用它。请注意,在投射对象时,它是,而不是在与对象进行交互时。

如果您已将方法标记为public,那么您的代码将显示。例如:

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

会打印

  

Derived2类Derived1类

但是,将代码更改为以下内容会在这种情况下显示new的问题:

void Main()
{
    Derived2 d = new Derived2();

    Derived1 e = new Derived1();
    ExecuteIt(d);
    ExecuteIt(e);
}

void ExecuteIt(Baseclass obj)
{
    obj.fun();
}

打印

  

基类基类

由于对象被强制转换为Baseclass,因此隐藏不会生效。要正确实现覆盖,您需要执行以下操作:

class Baseclass
{
    public virtual void fun()
    //     ^^^^^^^
    {
        Console.Write("Base class" + " ");
    }
}
class Derived1 : Baseclass
{
    public override void fun()
//  ^^^^^^ ^^^^^^^^
    {
        Console.Write("Derived1 class" + " ");
    }
}
class Derived2 : Derived1
{
    public override void fun()
//  ^^^^^^ ^^^^^^^^
    {
        Console.Write("Derived2 class" + " ");
    }
}

当运行时:

void Main()
{
    Derived2 d = new Derived2();

    Derived1 e = new Derived1();
    ExecuteIt(d);
    ExecuteIt(e);
}

void ExecuteIt(Baseclass obj)
{
    obj.fun();
}

正确输出

  

Derived2类Derived1类