I have this as one of my members of the class 'KeyEvent':
private delegate void eventmethod();
And the constructor:
public KeyEvent(eventmethod D)
{
D();
}
What I want to do is instead of calling D() there, I want to store that method (D) as a member variable of KeyEvent, so something like:
stored_method = D();
And then later in another method of KeyEvent, do something like:
stored_method();
How can I do this?
the thing that you want is called "first class function" http://en.wikipedia.org/wiki/First-class_function
C#, since version 3, supports anonymous functions and lambda expressions.
So you can use
Func<A,R>
which represents a function taking an argument of type A and returning a value of type Rfrom wiki
Couple things... PascalCase types/delegates/etc (EventMethod) and camelCase arguments (d, dIsMyMethod). And reuse what the framework gives you:
private Action hurr;
You could do something like:
Which can be instantiated by:
Where MyFunction is the name of some function in that class
The KeyEvent class can then invoke that function with:
The Action class also allows strongly typed parameters to be passed in and the Func class can be used for methods that return a result.
You pretty much have the code already. Just create a member field of the right delegate type and save the parameter to it just like you would with any other data type.