简体   繁体   中英

How can I access the result in Derived 1 and Derived 2 and not the base class

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

How can I access the result in Derived 1 and Derived 2 and not the base class Is this overloading or overriding?

new is neither overloading nor overriding. It essentially says 'When I am called, and the object is cast as Derived1 , then invoke this'. Note that it's when the object is cast , rather than whenever the object is interacted with.

Your code would appear to work, if you had marked the methods as public . For example:

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

Would print

Derived2 class Derived1 class

However, changing your code to the following will reveal the problem with new in this case:

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

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

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

Prints

Base class Base class

Since the object is cast as Baseclass , and thus the hiding doesn't take effect. To properly implement overriding, you need to do the following:

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" + " ");
    }
}

Which, when run with:

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

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

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

Properly outputs

Derived2 class Derived1 class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM