2017-08-15 139 views
0

一類的所有兒童的方法,您說,我有一個,每1秒調用的方法是「定時」級,並呼籲在類「齒輪」的另一種方法:從另一個調用類

public class Timer 
{ 
    public void OnTick() 
    { 
     Gear.Update(); 
    } 
} 

public class Gear 
{ 
    public static void Update() { } 
} 

這種工作,但它只在基類上調用。 方法「更新」應該被稱爲「齒輪」的所有兒童: e.g:

public class AnotherClass : Gear 
{ 
    public override void Update() { // do stuff } 
} 
public class YetAnotherClass : Gear 
{ 
    public override void Update() { // do stuff } 
} 
public class AndAnotherClass : Gear 
{ 
    public override void Update() { // do stuff } 
} 

我怎樣才能做到這一點?

+0

所以你要撥打齒輪的所有子類的所有實例?聽起來就像你想在某種容器中運行你的代碼。 –

+1

集合中的痛處對象引用,然後遍歷它們並調用Update() – OldProgrammer

+2

您的代碼沒有意義。您可以像調用靜態方法一樣調用Gear.Update(),但將其定義爲實例方法。 –

回答

3

爲了使代碼工作,你想要的方式,你需要做這樣的事情(我會擔心內存泄漏):

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

但是,您可能更好斷通過如此限定基礎案例:

public abstract class Gear 
{ 
    public abstract void Update(); 
} 

,然後定義一個集合類:

public sealed class GearCollection : List<Gear> 
{   
    public void Update() 
    { 
     foreach (var gear in this) 
      gear.Update(); 
    } 
} 

然後

public static void Main(string[] args) 
{ 
    var gears = new GearCollection(); 

    //add gear instancs to gears 

    var timer = new Timer(o => gears.Update(), null, 0, SOME_INTERVAL);    
} 
+0

雖然是合理的,但我不明白這段代碼如何滿足「我必須在沒有實例化的情況下調用它」(我完全不知道實際的限制是什麼,但是編寫它的這篇文章肯定需要實例化對象)。您可能希望與OP一起澄清問題,以便實際回答。 –

+0

很好的破解! 「*可能*」是輕描淡寫。 –