简体   繁体   中英

Accessing an overridden base class member using a derived class object (C#)

Given 2 Types

class A { public virtual void Hello() { Console.WriteLine("A"); } }
class B : A { public override void Hello() { Console.WriteLine("B"); } }

and an instance of 'B' B b = new B();

Can I access the Hello() method of A thru b ? (I can think of exposing A as property in B but not sure if there is another way)

I knew this is possible in c++ but was scratching my head in c#.

PS :Please no conversations around 'why do you want this?' or 'this is a bad design' etc.

Not from the outside.

From the inside , the instance can call that, via base.Hello() , so you could add a:

public void Foo() { base.Hello(); }   

It is not possible in c#. Sorry.

You can try shadowing:

class A { public virtual void Hello() { Console.WriteLine("A"); } }
class B : A { public new void Hello() { Console.WriteLine("B"); } }

Then you can do:

        A b = new B();
        b.Hello(); //prints A
       (B)b).Hello(); //prints B

       B b1 = new B();
       b1.Hello(); //prints B

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