Reputation: 65996
Let's say I want to store a group of function pointers in a List<(*func)>
, and then later call them, perhaps even with parameters... Like if I stored in a Dict<(*func), object[] params>
could I call the func with the parameters? How would I do this?
Upvotes: 19
Views: 26925
Reputation: 34810
You can absolutely have a dictionary of functions:
Dictionary<string, Action<T>> actionList = new Dictionary<string, Action<T>>();
Dictionary<string, Func<string>> functionList = new Dictionary<string, Func<string>>();
actionList.Add("firstFunction", ()=>{/*do something;*/});
functionList.Add("firstFunction", ()=>{return "it's a string!";});
You can then call the methods like this:
string s = functionList["firstFunction"].Invoke();
Upvotes: 22
Reputation: 4048
If you are only storing event handlers then...
Dictionary<string, EventHandler> dictEvents = new Dictionary<string, EventHandler>();
dictEvents.Add("Event1", someEventHandler);
...
protected void someEventHandler(object sender, EventArgs e)
{
//Do something.
}
Edit:
Upvotes: -1
Reputation: 54854
There are a couple ways you could do this. You could do it as others have suggested through the use of delegates. But to get the dictionary to work, they would all need the same signature.
var funcs = new Dictionary<Action<object[]>, object[]>();
Or if they have different signatures you could use the actual reflected method, like the following
var funcs = new Dictionary<MethodInfo, object[]>();
Upvotes: 2
Reputation: 161773
.NET uses delegates instead of function pointers. You can store a delegate instance like any other kind of object, in a dictionary or otherwise.
See Delegates from the C# Programming Guide on MSDN.
Upvotes: 35
Reputation: 283634
Look at the C# documentation on delegates, which is the C# equivalent of a function pointer (it may be a plain function pointer or be curried once to supply the this parameter). There is a lot of information that will be useful to you.
Upvotes: 8