如何将单个对象 [] 传递给参数对象 [] [英] How to pass a single object[] to a params object[]
问题描述
我有一个接受 params object[] 的方法,例如:
I have a method which takes params object[] such as:
void Foo(params object[] items)
{
Console.WriteLine(items[0]);
}
当我将两个对象数组传递给这个方法时,它工作正常:
When I pass two object arrays to this method, it works fine:
Foo(new object[]{ (object)"1", (object)"2" }, new object[]{ (object)"3", (object)"4" } );
// Output: System.Object[]
但是当我传递单个对象[]时,它不会将我的对象[]作为第一个参数,而是将其所有元素像我想一个一个地传递一样:
But when I pass a single object[], it does not take my object[] as the first param, instead it takes its all elements like I wanted to pass them one by one:
Foo(new object[]{ (object)"1", (object)"2" });
// Output: 1, expected: System.Object[]
如何将单个 object[] 作为第一个参数传递给 params 数组?
How do I pass a single object[] as a first argument to a params array?
推荐答案
一个简单的类型转换将确保编译器知道你在这种情况下的意思.
A simple typecast will ensure the compiler knows what you mean in this case.
Foo((object)new object[]{ (object)"1", (object)"2" }));
由于数组是对象的子类型,所以这一切都成立.不过有点奇怪,我同意.
As an array is a subtype of object, this all works out. Bit of an odd solution though, I'll agree.
这篇关于如何将单个对象 [] 传递给参数对象 []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!