简体   繁体   中英

How can I use params in a delegate function?

I want to be able put any amount of variables in the method I make with the delegate. I thought this was usually how you do it but it doesn't seem to be working.

I'm trying to do it with the h(x,y,z) here

delegate double MyFunction1(double x);
delegate double MyFunction2(double x, double y);
delegate double MyFunction(double x, params double[] args);

static void Main(string[] args)
{
    MyFunction1 f = x => x;
    MyFunction2 g = (x,y) => x * y;

    MyFunction h = (x, y, z) => x * y * z;
}

You need to define h as a method that acceps A double[] . a params is called as seperate arguments, but is passed to the method as one array:

delegate double MyFunction(params double[] args);

static void Main(string[] args)
{
    MyFunction h = args => { 
        var result = 1.0; 
        foreach (var value in args) { result *= value; }; 
        return result; 
    };
}

Then you can call it like this:

h(3,4,5)

See the examples over here

params allows the caller to pass in any number of arguments. It doesn't allow the callee to handle any number of arguments they want.

So h must be able to handle any positive number of arguments. It needs to be written like this:

MyFunction h = (x, rest) => ...;

x is a double , and rest is a double[] that can contain 0 or more elements.

If you want to compute the product of all the arguments:

MyFunction h = (x, rest) => x * rest.Aggregate(1.0, (y, z) => y * z);

If you want to handle only 3 arguments, use such a delegate instead:

delegate double MyFunction3(double x, double y, double z);

There is no delegate type that allows you to specify how many arguments you want to handle. After all, how would the caller know how many arguments to give you?

Try this.

delegate double MyFunction(double x, params double[] args);
class Program
{
    static public double Hoo(double x, params double[] args)
    {
        foreach (var item in args)
        {
            x *= item;
        }
        return x;
    }
    static void Main(string[] args)
    {
        MyFunction h = Hoo;
        Console.WriteLine($"h (with 1 params) : {h.Invoke(5)}");
        Console.WriteLine($"h (with 2 params) : {h.Invoke(5, 5)}");
        Console.WriteLine($"h (with 3 params) : {h.Invoke(5, 5, 5)}");
        Console.WriteLine($"h (with 4 params) : {h.Invoke(5, 5, 5, 5)}");
    }
}

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