0

Is it possible for a parent class to contain a list of all the subclasses?

I have two classes here and they are as follows

public class Event{

    List<Event> events = new <Event>();
    // etc
}

public class Message : Event{
    string text; 
    // etc
}

In this scenario, (in Main) I can draw event.First() which could be a message (textbox), then delete the event. Does this have any problems? this is for an RPG dialogue system. (Other events will be input boxes, etc)

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
SBM
  • 3
  • 4
  • http://stackoverflow.com/questions/8928464/for-an-object-can-i-get-all-its-subclasses-using-reflection-or-other-ways Top answer here seems to have what you're looking for. – Aneesh Ashutosh Jul 16 '13 at 19:17
  • Maybe you want to define your event types as an enumeration instead? Then Enum.GetValues and associated static methods should help you do these type of operations – Alan Jul 16 '13 at 19:18

1 Answers1

0

Use some sort of queue

void Main()
{
    Events.Queue(new Message(){ Text = "Hit points +5" });
    Events.Queue(new Message(){ Text = "Hit points +6" });
    Events.Queue(new Message(){ Text = "Hit points +7" });

    while(Events.HasNext())
    {
        Console.WriteLine(Events.GetNext().Text);
    }
}

public static class Events
{
    private static Queue<Message> messages = new Queue<Message>();

    public static void Queue(Message message)
    {
        messages.Enqueue(message);
    }

    public static Message GetNext()
    {
        return messages.Dequeue();
    }

    public static bool HasNext()
    {
        return messages.Count > 0;
    }
}

public class Message
{
    public string Text {get; set;}
}

In a more dynamic way, you can use interfaces to build a simple render system.

void Main()
{
    Events.Queue(new Message(){ Text = "Hit points +5" });
    Events.Queue(new Message(){ Text = "Hit points +6" });
    Events.Queue(new ChuckNorris());

    SpriteBatch sb = new SpriteBatch(...);
    while(Events.HasNext())
    {
        Events.GetNext().Render(sb);
    }
}

public static class Events
{
    private static Queue<IRenderable> renderables = new Queue<IRenderable>();

    public static void Queue(IRenderable renderable)
    {
        renderables.Enqueue(message);
    }

    public static IRenderable GetNext()
    {
        return renderables.Dequeue();
    }

    public static bool HasNext()
    {
        return renderables.Count > 0;
    }
}

public interface IRenderable
{
    void Render(SpriteBatch sb);
}

public class Message : IRenderable
{
    public string Text {get; set;}

    public void Render(SpriteBatch sb)
    {
        // ... render code
    }
}

public class ChuckNorris : IRenderable
{
    public void Render(SpriteBatch sb)
    {
        // render code
    }
}
Charlie Brown
  • 2,817
  • 2
  • 20
  • 31