开发者

Getting the actual type from reflection fieldInfo

开发者 https://www.devze.com 2023-04-07 04:43 出处:网络
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 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 t开发者_运维百科hen 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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号