C# Action/Function List

后端 未结 2 1027
無奈伤痛
無奈伤痛 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 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).

提交回复
热议问题