简体   繁体   中英

Getting the actual type from reflection fieldInfo

I'm writing a generic wrapper around a software's GUI API which has the ability to process quite a few of its own 'built-in' types but I can't figure out how to get it what it needs. For example, I'm doing this to handle strings:

("MakeTextField" and "MakeField" are pseudo-code, which take a value, display a GUI element and then return the value from the GUI for storage)

public static void FieldInfoMakeField<T>(T instance, System.Reflection.FieldInfo fieldInfo)
{
    string label = fieldInfo.Name;

    if (fieldInfo.FieldType == typeof(string))
    {
        var val = (string)fieldInfo.GetValue(instance);
        val = MakeTextField(label, val);
        fieldInfo.SetValue(instance, val);
        return;
    }
    //else if ... more types

This is what I have for the API's type where A and B are derrived from a common type, which I can also test for, but I need the derrived type:

...
else if (fieldInfo.FieldType == typeof(APITypeA))
{
    var val = (APITypeA)fieldInfo.GetValue(instance);
    val = MakeField<APITypeA>(label, val);  // My version, casts internally
    fieldInfo.SetValue(APITypeA, val);
    return;
}
else if (fieldInfo.FieldType == typeof(APITypeB))
{
    var val = (APITypeB)fieldInfo.GetValue(instance);
    val = MakeField<APITypeB>(label, val);  // My version, casts internally
    fieldInfo.SetValue(APITypeB, val);
    return;
}
...

This all works, but I have about 10 more copy&paste code blocks for other "APITypes". If I wasn't doing this generically, I would just pass in any type derived from the API's base type and it would work, but I can't figure out how to get the fieldInfo's actual type. If I print it, it will print the name of the derived types, but I can't seem to get them out.

I hope I'm stating my problem well enough. This is highly situational but seems like it should be possible. If I could just get the type that FieldType() prints, I would be gold. Otherwise I have #regions full of else if statements, which certainly isn't as generic as I would like!

Are you able to provide the Type of the field to the FieldInfoMakeField function?

public static void FieldInfoMakeField<T, V>(T instance, FieldInfo fieldInfo)
{
    string label = fieldInfo.Name;

    var val = (V)fieldInfo.GetValue(instance);
    val = MakeField<V>(label, val);
    fieldInfo.SetValue(instance, val);
    return;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM