dimanche 30 septembre 2018

Perform a 'task' via an enum and a field, by checking the 'T' type, and inferring it into the task automatically

I've come across an issue that I cannot solve. I've got an IReadOnlyList of classes that each have a bunch of fields. These fields have names (variable names) identical to a list of enums. Think that for each field that exists, an enum for it with the exact same name also exists (so object helloHi has an equivalent enum something { helloHi }).

What I've attempted to do is compare the two field names. If they are identical, perform a function on them. The problem is that the function needs to infer a T from the variable, and since reflection isn't able to pull that 'T' without some form of cast, it won't proceed.

This is the code:

public class Something() {

    [BackgroundTask]
    private void load(Overlay param_1, Config param_2) {
        Children = new Drawable[] // is the IReadOnlyList
        {
            SomethingClass(param_1),
            AnotherClass(param_2)
        }

        performTask(this, param_2);
    }
}

public class Config {

    public void task<U>(SomeEnums se, ValueType<U> value) // do the task
}

public class SomethingClass {

    ValueType<double> someDouble = new ValueType<double>();
    ValueType<int> someInt = new ValueType<int>();
}

public enum SomeEnums {
    someDouble,
    someInt,
}

void performTask(Something the_class, Config the_config) {
    // ... for each field within the_class, do (uses reflection)
    field => {
        foreach (SomeEnums enums in Enum.GetValues(typeof(SomeEnums)))
        {
            if (field.Name == enums.ToString()) {
                the_config.task(enums, field.GetValue(null)); // cant infer 'U' from an 'object'
            }
        }
    }
}

Technically, I could just do the config.task within the class where the types are known and visible, but I'd much prefer to automate it from here, so that it doesn't need 2-3 changes every time a new variable is created.

One of the strategies I am aware of is performing an if check within the performTask like such:

// performTask, field =>, foreach
{
    if (field.FieldType == ValueType<double>)
        config.task(enums, (ValueType<double>)field.GetValue(null));
} //etc

However, I don't like this method. Would there be a better way to perform what I want?





Aucun commentaire:

Enregistrer un commentaire