C#对象数组 [英] C# object to array
问题描述
使用反射,我有一个对象,我需要将该对象转换为可迭代的项目列表(类型未知,将是对象).使用监视"窗口,我可以看到我的对象是某种类型的数组,因为它告诉我元素的数量,并且可以分解树视图以查看元素本身.
Using reflection I have an object which I need to cast into an iterable list of items (type unknown, will be object). Using the Watch window I can see my object is an array of some type as it tells me the number of elements and I can explode the tree view to see the elements themselves.
首先,我需要检查传递的对象是否为某种数组(可能是List,可能是object [],等等).然后,我需要遍历该数组.但是,我无法进行类型转换.
Firstly, I need to check that the object passed is some kind of array (might be List, might be object[], etc). Then I need to iterate through that array. However, I can't do the type conversion.
这是我的使用方式(缩写):
Here's how I'm using it (abbreviated):
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()方法不知道该属性的基本类型.
I've tried various different casts. The above doesn't raise an exception but mylist is null when anArray actually exists and contains items. The actual instance being saved is a strongly-typed List<> but could take a limited subset of forms if necessary. But the point of the exercise is that this Example() method doesn't know the basic type of the property.
推荐答案
仅当对象实际上是 是ArrayList时,才能将其投射到ArrayList.例如,它不能与System.Array或System.Collections.Generic.List`1一起使用.
Casting it to an ArrayList is only going to work if the object actually is an ArrayList. It wont work with a System.Array, or a System.Collections.Generic.List`1 for example.
我认为您实际上应该将其转换为IEnumerable,因为这是您循环访问它的唯一要求...
I think what you actually should do is cast it to IEnumerable, since that is your only requirement to loop over it...
object anArray = propInfo.GetValue(instance, null);
IEnumerable enumerable = anArray as IEnumerable;
if (enumerable != null)
{
foreach(object element in enumerable)
{
// etc...
}
}
这篇关于C#对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!