C# Action/Function List

后端 未结 2 1028
無奈伤痛
無奈伤痛 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:43

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

    0 讨论(0)
  • 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<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);
       ...............
      }
    
    
    }
    
    0 讨论(0)
提交回复
热议问题