How would one best go about allowing the input of a c# program to control method invocation? For example:
Assume we have a delegate type:
delegate void WriteMe();
And a couple of methods:
void PrintInt() { Console.WriteLine(10); }
void PrintString() { Console.WriteLine("Hello world."); }
And allowing the input to select the invocation order:
public static WriteMe ProcessInvocationInput(int[] val) {
WriteMe d = null;
foreach (int i in val) {
switch (i) {
case 1: d += PrintInt; break;
case 2: d += PrintString; break;
}
}
}
And the code that calls it all:
static void Main(string args[]) {
int[] values = {1, 2, 3}; // Obviously this array could be filled
// from actual input (args, file, wherever)
WriteMe d = ProcessInvocationInput(values);
d();
}
The reason I’m posting this question is because it seems rather complex to implement what seems like a simple idea. I know another way to accomplish this behavior is with the reflection API, but that would be even more convoluted.
That really depends on the scope you’re trying to cover. For simple cases you could use a switch (I’d suggest and enum to make it clear):
But if you’re writing a shell, than you need something more robust, like some sort of
IExecutableCommandinterface implemented by various classes.You will have to implement some parser to handle multiple invocation requests and/or handle more complex arguments.
If you want to use Reflection, be sure to validate your input! That could be done by only executing methods with a custom attribute on them.
Filtering out methods with this attribute is easy enough: