简体   繁体   中英

Can I use a lambda expression with params keyword?

Lets say I have the following code:

delegate int MyDel (int n);   // my delegate

static int myMethod( MyDel lambda, int n) { 
    n *= n;
    n = lambda(n);
    return n;      // returns modified n
}

This way, having different lambda expression I can tune the output of the Method.

myMethod ( x => x + 1, 5);
myMethod ( x => x - 1, 5);

Now, if I don't want to do any aritmethic in lambda expression, I could use:

myMethod ( x => x, 5);  // and lambda will simply return x

My question is, is there a way to use the lambda expresion with 'params' optional properties? Maybe somehow embedding my delegate in array?

 static int myMethod (int n, params MyDel lambda) { 

Does this work?

EDIT Sorry, was doing this with one eye, let me rephrase that.

static int myMethod (int n, params  MyDel[] lambdas) {

Yes you can.

    delegate int MyDelegate(int n);
    static void MyMethod(int n, params MyDelegate[] handlers)
    {
        for (int i = 0; i < handlers.Length; i++)
        {
            if (handlers[i] == null)
                throw new ArgumentNullException("handlers");
            Console.WriteLine(handlers[i](n));
        }
    }

    static void Main(string[] args)
    {
        MyMethod(1, x => x, x => x + 1);
        Console.Read();
    }

Output:

1

2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM