Why don't Funcs accept more than 16 arguments?

后端 未结 6 959
情话喂你
情话喂你 2021-02-05 04:54

Since Javascript is the language that I am the most proficient at, I am familiar with using functions as first-class objects. I had thought that C# lacked this feature, but then

6条回答
  •  误落风尘
    2021-02-05 05:30

    You can just define any delegate you need. So a Func with 20 parameters would be defined like this:

    public delegate R Func<
        P0, P1, P2, P3, P4, P5, P6, P7, P8, P9,
        P10, P11, P12, P13, P14, P15, P16, P17, P18, P19, R>(
            P0 p0, P1 p1, P2 p2, P3 p3, P4 p4,
            P5 p5, P6 p6, P7 p7, P8 p8, P9 p9,
            P10 p10, P11 p11, P12 p12, P13 p13, P14 p14,
            P15 p15, P16 p16, P17 p17, P18 p18, P19 p19);
    

    You could then use it like this:

    Func<
            int, int, int, int, int, int, int, int, int, int,
            int, int, int, int, int, int, int, int, int, int, int> f = (
                p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10,
                p11, p12, p13, p14, p15, p16, p17, p18, p19) =>
                    p0 + p1 + p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9 + p10
                        + p11 + p12 + p13 + p14 + p15 + p16 + p17 + p18 + p19;
    
    var r = f(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
    

    C# also lets you use lambda syntax on any delegate, so you could also do this:

    public delegate R ArrayFunc(params P[] parameters);
    

    And then use it like so:

    ArrayFunc af = ps => ps.Sum();
    
    var ar = af(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
    

    It's a very flexible and powerful feature of the language.

提交回复
热议问题