1
Answer

syntax/method for storing/referring to many possible class instances?

wadeontheweb

wadeontheweb

20y
2.2k
1
Is there a way to put one of many possible class instances in some sort of variable container and refer to its methods when you don't know which class it is? Below is an example of what I am trying to do. Am I going about this all wrong or is there a correction I can make to the syntax to make it work? The point of the code below: I have a class that manages many other instances of different timeframes used for reporting. In this example I create two different instances, one from calss PerDayTimeFrame and one class from PerWeekTimeFrame. Then I want to be able to specify which one I will be using for the moment with method setTimeFrame(). Then later I want to call the current timeframe without having to know which one it is. I call tellCurrentTimeFrameToDoSomething() but get an error because I can't refer to the method in the instance through the member this.currentTimeFrame that I stored it in. public class TimeFrames { private object currentTimeFrame; private PerDayTimeFrame perDayTF; private PerWeekTimeFrame perWeekTF; public TimeFrames() { this.perDayTF = new PerDayTimeFrame(); this.perWeekTF = new PerWeekTimeFrame(); } public void setTimeFrame( string currentTF ) { switch(currentTF) { case "perDayTF": this.currentTimeFrame = (PerDayTimeFrame)this.perDayTF; break; case "perWeekTF": this.currentTimeFrame = (PerWeekTimeFrame)this.perWeekTF; break; } } public void tellCurrentTimeFrameToDoSomething() { this.currentTimeFrame.doSomething(); //ERROR! can't find method. } }
Answers (1)