简体   繁体   English

使用反射在任意对象上找到数组属性?

[英]Find an array property on an arbitrary object using reflection?

I have some generated classes which are similar in form but have no inheritance relationships, like this: 我有一些生成的类,它们的形式相似但没有继承关系,例如:

class horse {}
class horses { public horse[] horse {get;}}
class dog {}
class dogs { public dog[] dog {get;}}
class cat {}
class cats { public cat[] cat {get;}}

I want to write a method like: 我想写一个像这样的方法:

ProcessAnimals<T>(Object o)
{
 find an array property of type T[]
 iterate the array
}

So then I might do: 因此,我可能会这样做:

horses horses = ...;
ProcessAnimals<horse>(horses);

It seems like something reflection can be used for but what would that look like? 似乎可以使用反射功能,但是会是什么样呢?

You can iterate over the properties checking for arrays type: 您可以遍历检查数组类型的属性:

void ProcessAnimals<T>(object o)
{
    var type = o.GetType();

    var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                    .Where(pi => pi.PropertyType.IsArray && pi.PropertyType.GetElementType().Equals(typeof(T)));

    foreach (var prop in props)
    {
        var array = (T[])prop.GetValue(o);

        foreach (var item in array)
        {
            //Do something
        }
    }
}

I can suggest other way of doing this, without reflection, because all of this classes are basically the same: 我可以建议采取其他方式,而无需进行反思,因为所有这些类基本上都是相同的:

enum AnimalType
{
Horse,
Dog,
Cat
}
class Animal
{
public AnimalType Type;
}
class Animals
{
public Animal[] Animals { get; }
}
ProcessAnimals(Animals animals)
{
// do something with animals.Animals array
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM