Lars Holdgaard
Lars Holdgaard

Reputation: 9986

List of delegates and invoking

I am creating a smaller RPG game in ASP.NET. In this game I have an items architecture, where each item has some methods. For instance, all items should share a method like "Drop", "Examine" and "Use". Some items will have to be extended with methods like "Operate", "Calculate" and such.

So far, I have created the following object GameActionList:

public delegate void MyDelegate();

public class GameActionList
{
    public List<MyDelegate> Items = new List<MyDelegate>();

    public void Add(MyDelegate del)
    {
        Items.Add(del);
    }

    public void CallDelegates()
    {
        foreach (MyDelegate myDelegate in Items)
        {
            myDelegate();
        }
    }
}

I have a BaseItem class, which has this GameActionList. The get property of this in the BaseItem class is like this:

    public GameActionList Actions 
    { 
        get
        {
            GameActionList actions = new GameActionList();
            actions.Add(this.Drop);
            actions.Add(this.Examine);
            return actions;
        }
    }

This is fine, BUT... I have some problems!

My problem

I need a way more generic GameActionList. I need to have a list of not only voids, but also functions.. Also, I need both methods with parameters and without parameters.

For instance: The Drop method will need a Player object, so he can Drop the item. The Examine method will need to return a string descriping the item.

Also, I need some data which I don't know when I Initialize the GameActionList: I first know these data when I invoke the method...

So I have two questions:

  1. How do you extend the GameActionList, so it can contain a list of both voids and functions andalso these both can have parameters or not.. (AND DOES IT EVEN MAKE SENSE??)
  2. How can I give some data to the method later in the cycle, like when invoking?

Also... This might be a very stupid way to do it, so if you have some way more elegant solution.. I'm more than ready to hear it!

Thanks a lot...! Lars

Upvotes: 7

Views: 12687

Answers (1)

TalentTuner
TalentTuner

Reputation: 17556

you most probably need Action , Func delegates

Func

Action

Upvotes: 7

Related Questions