如何从System.Array中转换为对象[]在C# [英] How do I convert from System.Array to object[] in C#

查看:186
本文介绍了如何从System.Array中转换为对象[]在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个COM函数要求 [对象] 作为一个参数:

I have a COM function that expects object[] as a parameter:

foo(object[] values)

我想通过一些枚举字段,所以我使用了以下内容:

I want to pass some enum fields to it so I use the following:

object[] fields = (object[])Enum.GetValues(typeof(SomeEnumType));

然而,当我试图通过字段富(...)即[ FOO(场)]我得到一个错误:

However, when I try to pass fields to foo(...) i.e. [foo(fields)] I get an error:

无法投类型的对象`SomeEnumType []'输入'System.Object的[]'。

"Unable to cast object of type `SomeEnumType[]' to type 'system.Object[]'.

谁能告诉我什么,我做错了什么?

Can anyone tell me what I'm doing wrong?

推荐答案

作为异常说,你不能转换蒙上了 SomeEnumType [] [对象] - 前者是一个数组,其中每个值为 SomeEnumType 值;后者是一个阵列,其中每个元素是一个参考

As the exception says, you can't convert cast a SomeEnumType[] to object[] - the former is an array where each value is a SomeEnumType value; the latter is an array where each element is a reference.

使用LINQ,你可以创建一个的阵列很轻松地:

With LINQ you can create a new array easily enough:

object[] fields = Enum.GetValues(typeof(SomeEnumType))
                      .Cast<object>()
                      .ToArray();

这基本上都会中的每个元素(每一个枚举值)来创建一个的IEnumerable&LT;对象&gt; ,然后创建一个数组。它类似于提拉克的做法,但我preFER使用铸造的时候我并不真的需要一个通用的投影。

This will basically box each element (each enum value) to create an IEnumerable<object>, then create an array from that. It's similar to Tilak's approach, but I prefer to use Cast when I don't actually need a general-purpose projection.

或者

SomeEnumType[] values = (SomeEnumType[]) Enum.GetValues(typeof(SomeEnumType));
object[] fields = Array.ConvertAll(values, x => (object) x);

这篇关于如何从System.Array中转换为对象[]在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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