【问题标题】:C# object to arrayC# 对象到数组
【发布时间】:2011-09-20 05:58:04
【问题描述】:

使用反射我有一个对象,我需要将其转换为可迭代的项目列表(类型未知,将是对象)。使用 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 为空。实际保存的实例是一个强类型 List,但如有必要,可以采用有限的形式子集。但练习的重点是这个 Example() 方法不知道属性的基本类型。

【问题讨论】:

  • 您可以从 instance.GetType() 中找出对象的类型,您可以使用is 将其与desiredbale 类型进行比较,例如if (instance.GetType() is IEnumerable)
  • @Bad Display Name 这就是 is 关键字现在的工作方式,您在那里所做的是尝试从 System.Type 转换为 System.Collection.IEnumerable,这不会'不起作用,因为 System.Type 没有实现该接口。也许你的意思是 typeof(IEnumerable).IsAssignableFrom(instance.GetType())

标签: c# arrays reflection collections casting


【解决方案1】:

试试这个

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

【讨论】:

  • 如果是原始类型,这是最简单的方法。
【解决方案2】:

尝试投射到IEnumerable。这是所有可枚举、数组、列表等实现的最基本的接口。

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

【讨论】:

    【解决方案3】:

    如果它是任何类型(数组、列表等)的集合,您应该能够将其转换为 IEnumerablePropertyInfo 还包含一个 PropertyType 属性,如果您愿意,可以使用它来找出实际类型。

    【讨论】:

      【解决方案4】:

      试试这个:

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

      您可能还需要指定 IEnumerable 的泛型类型,具体取决于您的情况。

      【讨论】:

        【解决方案5】:

        只有当对象实际上一个 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...
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2018-03-12
          • 2012-03-11
          • 2011-04-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-12-25
          • 1970-01-01
          相关资源
          最近更新 更多