Can I put all of this code in one line, like "Level + index ()" Is it possible?
I have this switch function:
switch(index)
{
case 1:
Level1();
break;
case 2:
Level2();
break;
case 3:
Level3();
break;
case 4:
Level4();
break;
case 5:
Level5();
break;
}
as you can see, each index calls a function with the name "Level" and the index number.
Not like that, no. You could use delegates:
// Ideally make this a readonly field.
Action[] actions = { Level1, Level2, Level3, Level4, Level5 };
...
actions[index - 1]();
Or you could use reflection, as others have mentioned... but I'd try to avoid that if possible, especially if performance is a concern.
It does feel like an odd design though - I'd take a step back and consider whether there's a cleaner way of designing this to start with. (It's hard for us to help with that at the moment without more context.)
Try this:
typeof(yourClassCOntainingLevel1Method).GetMethod("Level"+index).Invoke(this,null);
yourClassCOntainingLevel1Method is a class name where you have Level1 method
if it's in the same class as calling:
typeof(this).GetMethod("Level"+index).Invoke(this,null);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With