开发者

Passing arrays to variable length argument lists

开发者 https://www.devze.com 2022-12-19 18:10 出处:网络
If I have a function void Foo(params int[] bar){} The following runs fine: int[] a1 = {1, 2, 3}; int[] a2 = {4, 5, 6};

If I have a function

void Foo(params int[] bar){}

The following runs fine:

int[] a1 = {1, 2, 3};
int[] a2 = {4, 5, 6};
Foo(1, 2, 3);
Foo(a1);

But these give compile errors:

Foo(a1, 1, 2, 3);
Foo(1, 2, a1);
Foo(1, a1, 2);
Foo(a1, a2, 1, 2, 3);

because only the first argument is allowed to be an int[], the开发者_运维技巧 rest have to be ints.

The final example is what I would like to do, but the language won't let me without combining the arrays first. I really like the simplicity of the syntax, and I would rather not add to the code more than I have to. Does anyone have a nice way to do this?


It's weird. Foo(a1, 2, 3) shouldn't work. You should either pass an array or a bunch of integers. You can't mix them AFAIK. Do you have another overload or something?

There's not really a neat syntax for doing that. The most concise one I can think of is:

Foo(a1.Concat(a2).Concat(new[] {1,2,3}).ToArray());


Agreed, its very odd Foo(a1, 2, 3) works.

Heres an extension method for .Concat to make Mehrdad's syntax a little easier on the eyes.

public T[] Concat<T>(this T[] first, params T[] other)
    {
        T[] output = new T[first.Length+other.Length];

        first.CopyTo(output,0);
        other.CopyTo(output,first.Length);
        return output;
    }

Can be used as follows:

Foo(a1.Concat(a2).Concat(1,2,3));
0

精彩评论

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