Store an operator in a variable

前端 未结 5 974
情深已故
情深已故 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:34

    Use a Function delegate;

    Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.

    void MyLoop(int start, int finish, Func op)
    {
        for(var i = start; i < finish; i = op(i))
        {
            //do stuff with i
        }
    }
    

    Then;

    MyLoop(15, 45, x => ++x);
    MyLoop(60, 10, x => --x);
    

    Here is a DEMO.

提交回复
热议问题