I have a series of functions that I want to have the following functionality.
- When the function is called, add itself to a list of functions remembering the parameters and values
- Allow the list of functions to be called at a later date
The different functions have a variety of different parameters and I'm struggling to think of an elegant way to do this. Any help would be appreciated.
Maybe you could some how use the
Delegate.DynamicInvoke(Object[] obj)
function. You could add each method to an object array, then loop through the array calling DynamicInvoke on each one.You could consider using a list of actions or functions
if you want to store parameters as well and have you could use a Func and store and use it in much the same way
You could also look at Tasks
EDIT:
looking at the answers that popped up while I was writing mine this solution is very similar to Brook's
I think this would meet your needs, however the functions are not "adding themselves".
One way to make the functions "add themselves" would be to use an AOP lib such as postsharp or linfu dynamic proxy, and add an interceptor which adds the function and args to the array. To do this would probably be more work than it would be worth IMO, as the above is much simpler and still achieves the desired functionality.
I'm not sure I understand your question, but I think you could use array of pointers to a functions(in C# it is called delegates). So when function is called, put function pointer in a list. In this way you can call function from list. Here is some idea. Notice when you add new delegate pointer to a list (
functionPointers
), in second listmyParameters
you add new object of typeParameters
which holds function parameters in public attribute calledparameters
. This means that delegatei
in listfunctionPointers
for parameters hasi
-th object in listmyParameters
. This is how you know which parameters, are for which function. Probably there are some betters solutions, but this is alternative.}
There's hardly an elegant solution to this. Since you said the methods would all have different signature, there's no way to store them in a single array as delegates. With that out of the way, next you can try is using reflection, storing each parameter value in object[], storing the method as MethodInfo, and then invoking it.
Edit: This is what I could come up with:
Then just invoke with
method.Invoke(method.ReflectedType, args)