Store an operator in a variable

前端 未结 5 973
情深已故
情深已故 2020-12-17 16:00

Is there a way to store an operator inside a variable? I want to do something like this (pseudo code):

void MyLoop(int start, int finish, operator op)
{
             


        
5条回答
  •  臣服心动
    2020-12-17 16:40

    I tried a different approach, using a class that defines operators and accessing via reflection - i.e. you can store your operators as strings. This allows for relational operators as well.

    class Program
    {
        static void Main(string[] args)
        {
            Operators ops = new Operators();
            object result = ops.Use("LessOrEqual", new object[] {3,2}); // output: False
            Console.WriteLine(result.ToString());
    
            result =  ops.Use("Increment", new object[] {3}); // output: 4
            Console.WriteLine(result.ToString());
            Console.ReadKey();
        }
    }
    
    public class Operators
    {
        public object Use(String methodName, Object[] parameters)
        {
            object result;
            MethodInfo mInfo = this.GetType().GetMethod(methodName);
            result = mInfo.Invoke(this, parameters); // params for operator, komma-divided
            return result;
        }
    
    
        public bool LessOrEqual(int a, int b)
        {
            if (a <= b)
            {
                return true;
            }
            else
            {
                return false; 
            }  
        }
    
        public int Increment(int a)
        {
            return ++a;
        }
    }
    

提交回复
热议问题