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:
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
Create the delegate and matching procedures Create a delegate named MySubDelegate . Declare a class that contains a method with the same signature as the delegate. Define a method that creates an instance of the delegate and invokes the method associated with the delegate by calling the built-in Invoke method.
The set of methods encapsulated by a delegate instance is called an invocation list. When a delegate instance is created from a single method, it encapsulates that method, and its invocation list contains only one entry.
There are two types of delegates, singlecast delegates, and multiplecast delegates. Singlecast delegate point to single method at a time.
Delegates allow methods to be passed as parameters. Delegates can be used to define callback methods. Delegates can be chained together; for example, multiple methods can be called on a single event. Methods don't have to match the delegate type exactly.
you most probably need Action , Func delegates
Func
Action
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With