How to pass a single object[] to a params object[]

前端 未结 7 1434
有刺的猬
有刺的猬 2020-11-27 15:43

I have a method which takes params object[] such as:

void Foo(params object[] items)
{
    Console.WriteLine(items[0]);
}

When I pass two o

相关标签:
7条回答
  • 2020-11-27 16:18

    One option is you can wrap it into another array:

    Foo(new object[]{ new object[]{ (object)"1", (object)"2" } });
    

    Kind of ugly, but since each item is an array, you can't just cast it to make the problem go away... such as if it were Foo(params object items), then you could just do:

    Foo((object) new object[]{ (object)"1", (object)"2" });
    

    Alternatively, you could try defining another overloaded instance of Foo which takes just a single array:

    void Foo(object[] item)
    {
        // Somehow don't duplicate Foo(object[]) and
        // Foo(params object[]) without making an infinite
        // recursive call... maybe something like
        // FooImpl(params object[] items) and then this
        // could invoke it via:
        // FooImpl(new object[] { item });
    }
    
    0 讨论(0)
提交回复
热议问题