vendredi 26 novembre 2021

Dynamically casting objects from FieldInfo.GetValue in c#

I'm trying to iterate through all the fields in an instance of a class and extract their name / data. The fields themselves are instances of custom classes for storing data with some specific features I needed. The following works:

        foreach (var v in typeof(CentralParams).GetFields())
        {

            if(v.GetValue(_centralParams).GetType() == typeof(BoolEventProperty))
            {
                BoolEventProperty prop = (BoolEventProperty) v.GetValue(_centralParams);
                print(v.Name + "   " + prop.Value);
            }
            
            if(v.GetValue(_centralParams).GetType() == typeof(FloatEventProperty))
            {
                FloatEventProperty prop = (FloatEventProperty) v.GetValue(_centralParams);
                print(v.Name + "   " + prop.Value);
            }
            
            if(v.GetValue(_centralParams).GetType() == typeof(IntEventProperty))
            {
               IntEventProperty prop = (IntEventProperty) v.GetValue(_centralParams);
               print(v.Name + "   " + prop.Value);
            }

        }

However I have to manually check for the type of the object in the field, then cast it to a new instance of that type in order to access the Value member. This is annoying as every time I add a new data type to the CentralParams class I will have to handle it explicitly here.

Is there a way I can dynamically cast it to an empty variable of the correct type?

v.GetValue(_centralParams).GetType() returns the type I need so seems like it should be possible.

Something along the lines of

            var type = v.GetValue(_centralParams).GetType();

            var prop = (type)v.GetValue(_centralParams);

Thanks





Aucun commentaire:

Enregistrer un commentaire