samedi 7 avril 2018

Check the type of a field received by reflection, and perform an action

To simply state, I just recently got into using reflection. While trying write code that could automate previously repetitive tasks for me, I came across a problem. I cannot correctly understand how to access the field that reflection returns to me as a FieldInfo. Here is my current code:

class cClass
{
    // these classes implement the IClass interface
    public static aClass _aClass = new aClass();
    public static bClass _bClass = new bClass();
}

// in another class
public List<IClass> aList = new List<IClass>();
public void init(cClass theClass)
{
    theClass.GetType()
        .GetFields(BindingFlags.Public | BindingFlags.Static)
        .ToList()
        .ForEach(field =>
        {
            if (field.FieldType == typeof(aClass))
                aList.Add(field) // this doesn't work, because FieldInfo doesn't inherit IClass
                aList.Add((aClass)field); // This doesn't work because I cannot cast
            // if bClass, then something similar
        });
}

How would I be able to check the type, and add it, potentially by casting the field which reflection has given into the type I check against. (I dislike using multiple if statements, so a switch statement would be better off)

e.g:

if (field.FieldType == typeof(aClass))
    aList.Add((field as aClass));





Aucun commentaire:

Enregistrer un commentaire