如何将单个对象[]传递给params对象[] [英] How to pass a single object[] to a params object[]

查看:123
本文介绍了如何将单个对象[]传递给params对象[]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这需要params对象的方法[],如:

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[]

我如何通过一个单一的对象[]作为第一个参数一个参数数组?

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.

编辑:Woops,typoed我的例子code

Woops, typoed my example code.

这篇关于如何将单个对象[]传递给params对象[]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆