Reputation: 343
So what I'm basically trying to do is create a dynamic menu framework in C#. I essentially have a menu element (just a rectangle with some text on it at this point), which contains a DoAction() method. This method is run whenever the rectangle is clicked. What I want is for the DoAction method to be able to be defined at runtime. So for example I could instantiate a menu element whose DoAction() method does function x(), then instantiate another menu element whose DoAction() method does function y(). What I have is something like this.
public class MenuElement {
public void DoAction(); // method I want to be dynamic
public MenuElement((text, height, width, etc), method myMethod){
DoAction = myMethod;
}
}
MenuElement m1 = new MenuElement(..., function x());
MenuElement m2 = new MenuElement(..., function y());
m1.DoAction(); // calls x()
m2.DoAction(); // calls y()
This is the kind of thing that I know how to do in Javascript, but I'm not as familiar with C#, and I suspect .Net will make me jump through a few more hoops than JS would. From what I'm reading I'm going to have to use delegates? I can't find any tutorials that I can really follow to easily.
Upvotes: 1
Views: 74
Reputation: 200
Use the Action-Class. In your example it would be:
public class MenuElement {
public Action DoAction; // method I want to be dynamic
public MenuElement((text, height, width, etc), Action myMethod){
DoAction = myMethod;
}
}
MenuElement m1 = new MenuElement(..., new Action(() => {
// your code here
});
MenuElement m2 = new MenuElement(..., new Action(() => {
// your code here
));
m1.DoAction(); // calls x()
m2.DoAction(); // calls y()
For more information see MSDN
Upvotes: 2
Reputation: 488
Yes, delegates are the way to go. You can make use of different flavours of the delegates Action and Func for your requirement. Is this what you are trying to achieve?
public class MenuElement
{
public MenuElement(string text, int height, int width, Action<object> myMethod)
{
DoAction = myMethod;
}
public Action<object> DoAction { get; private set; }
}
MenuElement m1 = new MenuElement("text", 10, 20, (obj) => { Console.WriteLine("MenuElement1"); });
m1.DoAction(null);
Action<object> y = (obj) =>
{
Console.WriteLine("MenuElement2");
};
MenuElement m2 = new MenuElement("text", 10, 20, y);
m2.DoAction(null); // calls y()
Upvotes: 1