开发者

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 开发者_StackOverflowmodified 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜