C#对象转换为数组

29

使用反射,我有一个对象需要转换为一个可迭代的项列表(类型未知,将是对象)。在 Watch 窗口中,我可以看到我的对象是某种类型的数组,因为它告诉我元素数量,我也可以展开树形视图查看元素本身。

首先,我需要检查传递的对象是否是某种数组(可能是 List,可能是 object[] 等)。然后我需要遍历该数组。但是,我无法进行类型转换。

这是我如何使用它的方式(缩写):

    private static void Example(object instance, PropertyInfo propInfo)
    {
        object anArray = propInfo.GetValue(instance, null);
        ArrayList myList = anArray as ArrayList;
        foreach (object element in myList)
        {
            // etc
        }
    }

我已经尝试了各种不同的强制类型转换。上面的代码没有引发异常,但是当anArray实际存在并包含项时,mylist为null。实际保存的实例是一个强类型的List <>, 但如果需要,可以采用有限的子集形式。但是这个Example()方法的重点在于它不知道属性的基本类型。


你可以通过 instance.GetType() 方法获取对象类型,并使用 is 运算符将其与所需类型进行比较,例如:if (instance.GetType() is IEnumerable) - Ruslan
1
@Bad Display Name 这不是 is 关键字的工作方式,你正在尝试将 System.Type 强制转换为 System.Collection.IEnumerable,这是行不通的,因为 System.Type 没有实现该接口。也许你想表达的是 **typeof(IEnumerable).IsAssignableFrom(instance.GetType())**。 - MattDavey
6个回答

52
将其转换成ArrayList仅在对象实际上是ArrayList时才有效。例如,它不适用于System.Array或System.Collections.Generic.List`1。
我认为你实际上应该将其转换成IEnumerable,因为这是你唯一需要遍历它的要求...
object anArray = propInfo.GetValue(instance, null);
IEnumerable enumerable = anArray as IEnumerable;
if (enumerable != null)
{
    foreach(object element in enumerable)
    {
        // etc...
    }
}

马特...是你吗?我是马龙...无论如何,这个不起作用,IEnumerable需要一个类型参数(也许在旧版本的.NET上可能是可行的) - Cloud
@Cloud:不正确。有IEnumerableIEnumerable<T> - Daniel Hilgarth

18

尝试将对象转换为IEnumerable。这是所有可枚举的基本接口,包括数组、列表等。

IEnumerable myList = anArray as IEnumerable;
if (myList != null)
{
    foreach (object element in myList)
    {
        // ... do something
    }
}
else
{
    // it's not an array, list, ...
}

不行 - 它需要一个类型参数,这样是行不通的。 - Cloud
@Cloud:不正确。有IEnumerableIEnumerable<T> - Daniel Hilgarth
如果你遇到了“使用泛型类型 'IEnumerable<T>' 需要 1 个类型参数”的错误,那么你需要使用 System.Collections 命名空间,因为 IEnumerable 的定义就在那里。IEnumerable<T> 位于 System.Collections.Generic 中。 - undefined

14

只需尝试此方法

 string[] arr = ((IEnumerable)yourOjbect).Cast<object>()
                             .Select(x => x.ToString())
                             .ToArray();

如果它是原始类型,这是最简单的方法。 - MSK

1

试试这个:

    var myList = anArray as IEnumerable;
    if (mylist != null)
    { 
        foreach (var element in myList)
        {
            // etc
        }
    }

根据您的情况,您可能还需要指定IEnumerable的泛型类型。


1
如果它是任何类型的集合(数组、列表等),你应该能够将其转换为 IEnumerable。此外,PropertyInfo 包含一个 PropertyType 属性,您可以使用它来查找实际类型(如果您想要的话)。

1

在我的情况下,我需要定义数据类型IEnumerable<string>

在我的情况下,我需要定义数据类型IEnumerable。
var myList = anArray as IEnumerable<string>;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接