C# Action/Function List

后端 未结 2 1030
無奈伤痛
無奈伤痛 2021-01-25 15:22

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,         


        
2条回答
  •  不思量自难忘°
    2021-01-25 15:54

    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 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);
       ...............
      }
    
    
    }
    

提交回复
热议问题