如何转换对象,对象[] [英] How to convert object to object[]

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

问题描述

我有一个对象,其价值可能会像 INT [] 或<$ C几种阵列类型中的一种$ C>的String [] ,我想将其转换为一个的String [] 。我第一次尝试失败:

I have an object whose value may be one of several array types like int[] or string[], and I want to convert it to a string[]. My first attempt failed:

void Do(object value)
{
    if (value.GetType().IsArray)
    {
        object[] array = (object[])value;
        string[] strings = Array.ConvertAll(array, item => item.ToString());
        // ...
    }
}



与运行时错误无法投类型的对象'System.Int32 []'键入'System.Object的[],这是有道理的回想,因为我的 INT [] 不包含盒装整数

with the runtime error Unable to cast object of type 'System.Int32[]' to type 'System.Object[]', which makes sense in retrospect since my int[] doesn't contain boxed integers.

打探后,我来到这个工作版本:

After poking around I arrived at this working version:

void Do(object value)
{
    if (value.GetType().IsArray)
    {
        object[] array = ((Array)value).Cast<object>().ToArray();
        string[] strings = Array.ConvertAll(array, item => item.ToString());
        // ...
    }
}



我猜这是确定的,但它似乎很令人费解。任何人有一个简单的方法?

I guess this is OK, but it seems pretty convoluted. Anyone have a simpler way?

推荐答案

您无需将其转换为一个数组和然后使用LINQ。你可以做到这一点更流媒体的方式,只在最后转换为数组:

You don't need to convert it to an array and then use LINQ. You can do it in a more streaming fashion, only converting to an array at the end:

var strings = ((IEnumerable) value).Cast<object>()
                                   .Select(x => x == null ? x : x.ToString())
                                   .ToArray();



(请注意,这将保留为空,而不是抛出一个异常。这也是罚款的任何的IEnumerable ,而不仅仅是阵列。)

(Note that this will preserve nulls, rather than throwing an exception. It's also fine for any IEnumerable, not just arrays.)

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

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