I have a program that has to execute a function acording to a Enum and I\'m wondering If there\'s another way to it than this:
enum FunctionType
{
Addition = 0,
Can't say I would recommend doing this but:
public static class Functions
{
public static Func<int, int, int> Add = (x, y) => { return x + y; };
}
Then you just call Functions.Add(1,1)
If you really have to use an enum for it then you could do:
public static class Functions
{
public static void Add()
{
Debug.Print("Add");
}
public static void Subtract()
{
Debug.Print("Subtract");
}
public enum Function
{
Add,
Subtract
}
public static void Execute(Function function)
{
typeof(Functions).GetMethod(function.ToString()).Invoke(null, null);
}
}
Then Functions.Execute(Functions.Function.Add)
(extra functions is because my enum was inside the Functions class).
If your functions contain same signature
then you can do something like this
enum FunctionType
{
Addition = 0,
Substraction = 1,
Mutiplication = 2,
Division = 3
}
void ExecuteFunction(FunctionType Function)
{
//variable will contain function to execute
public Func<int, int, int> functionToExecute= null;
switch(Function)
{
case FunctionType.Addition: functionToExecute=Addition;
break;
case FunctionType.Substraction: functionToExecute=Subsctration;
break;
...
default: ...
}
//Checking if not reached default case
if(functionToExecute!=null)
{
var result= functionToExecute(para1,para2);
...............
}
}