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?
views:
344answers:
6Look 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.
.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.
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[]>();
You can absolutely have a dictionary of functions:
List<string, Action<T>> actionList = new List<string, Action<T>>();
List<string, Func<string>> functionList = new List<string, Func<string>>();
actionList.Add("firstFunction", ()=>{//do something;});
functionList.Add("firstFunction", ()=>{return "it's a string!";});
You can then call the methods:
string s = functionList["firstFunction"].Invoke();