vendredi 17 août 2018

How to get static fields from another class using reflection?

We have a static class called VisualizationSettings that has ~20 instances of a struct we made called VisualizationSetting (singular).

I want to have another class pull in all the individual instances of VisualizationSetting from VisualizationSettings, and modify them.

I added a method to VisualizationSettings that should get and return all instances of VisualizationSetting, like so:

    public static FieldInfo[] GetFields(){
        Type myType = typeof(VisualizationSetting);
        FieldInfo[] myField = myType.GetFields();
        return myField;
    }

Then, in my other class, I access this FieldInfo[], iterate through it, and modify it, like so:

    FieldInfo[] myField = VisualizationSettings.GetFields();

    foreach (FieldInfo setting in myField) {
        VisualizationSetting value = (VisualizationSetting)setting.GetValue(null);

        /* A bunch of stuff to modify value */

        setting.SetValue(null, value);
    }

However I get an error on the line VisualizationSetting value = (VisualizationSetting)setting.GetValue(null); saying TargetException: Non-static field requires a target

My confusion is that as far as I'm aware, setting should static, since VisualizationSettings is a static class. Is there something I'm missing here?





Aucun commentaire:

Enregistrer un commentaire