c# - Call ALL children methods of a class from another class -


lets have "timer" class method every 1 second called, , calls method in class "gear":

public class timer {     public void ontick()     {         gear.update();     } }  public class gear {     public static void update() { } } 

this kinda works, it's called on base class. method "update" should called in childrens of "gear": e.g:

public class anotherclass : gear {     public override void update() { // stuff } } public class yetanotherclass : gear {     public override void update() { // stuff } } public class andanotherclass : gear {     public override void update() { // stuff } } 

how can this?

in order code work way want, you'd need (i worry memory leak):

public abstract class gear {     readonly static list<gear> gears = new list<gear>();      public gear()     {         gears.add(this);     }      public static void update()     {         foreach (var gear in gears)             gear._update();     }      protected abstract void _update(); }   public sealed class gear1 :  gear {     protected override void _update()     {         //do stuff     } }  public sealed class gear2 : gear {     protected override void _update()     {         //do stuff     } }  public sealed class gear3 : gear {     protected override void _update()     {         //do stuff     } }   public static void main(string[] args) {     var timer =            new timer(o => gear.update(), null, 0, some_interval);                        } 

however, might better off defining base case thusly:

public abstract class gear {     public abstract void update(); } 

and define collection class:

public sealed class gearcollection : list<gear> {             public void update()     {         foreach (var gear in this)             gear.update();     } } 

and then

public static void main(string[] args) {     var gears = new gearcollection();      //add gear instancs gears      var timer = new timer(o => gears.update(), null, 0, some_interval);             } 

Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -