mardi 18 octobre 2022

Find object properties of a certain type

I am trying to recursively build a list of all the properties of an object that are of a certain type. Recursion is needed because the object can hold arrays of objects which, in turn, may contain fields of a certain type.

So, if an object has a member of type Wanted, I want that object in the list.

class a
{
    Wanted m_var;
};

If an object has an array that contains other objects and these objects contain a member of type Wanted, I'd also like those added to the list.

class b
{
    int m_whatever;
    a[] m_vararray;
};

I've been trying all sorts of approaches, including Reflection but I am not getting anywhere. All the attempts were some variation of this

private IList<object> ListOfTypeWanted(object fields)
{
    IList<object> result = new List<object>();

    System.Reflection.MemberInfo info = typeof(object);
    object[] properties = type.GetProperties();

    foreach (var p in propoerties)
    {
        if (true == p.GetType().IsArray)
        {
            result.Add(ListOfTypeWanted(p));
        }
        else
        {
            Type t = p.GetType();
            if (p is WantedType)
            {
                result.Add(this);
            }
        }
    }
    return result;
}

I've also tried Linq statements using Where() but they did not get me any useful results either.

Does anyone know what the best way is to achieve this?





Aucun commentaire:

Enregistrer un commentaire