c# - How can I call the overrided methods of a specific object? -


lets have typical hierarchy this:

enter image description here

what want have specific move() implementation every class. if have next code:

list<vehicle> vehicles = getvehicles(); foreach (vehicle v in vehicles)  {     v.move();  } 

the call has made corresponding move() implementation depending on class of v in runtime

i tried virtual , override if call move() in redcar instance, jumps car.move() (i guess because next override under vehicle)

any clue how can done?

here sample code works. had code handy thought of posting it.

public class vehicle {     public virtual void move()     {         console.writeline("vehicle moving");     } } public class car : vehicle {     public override void move()     {         console.writeline("car moving");     } }  public class redcar : vehicle {     public override void move()     {         console.writeline("red car moving");     } }  class program {      static void main(string[] args)     {         var vehicles = new list<vehicle>             {                 new redcar(), new car(),new vehicle()             };         foreach (var vehicle in vehicles)         {             vehicle.move();         }     } } 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -