jeudi 25 mars 2021

Getting value of a generic inherited private field

I'm having some trouble trying to access private fields from an inherited generic class. It throws me an exception with the object owner I'm using to try to get the value, but if I use that same owner to get the field from a field directly declared with that generic type it works fine.

Here's my fields:

public class Bool : DebugProperty<bool>
{
    ...
}

DebugProperty<bool> m_nonIngeriteedBool;
Bool m_inheritedBool;

Here's how I get the value from m_nonIngeriteedBool field:

FieldInfo field = owner.GetType().GetField(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);

Type type = field.FieldType;

FieldInfo m_value = type.GetField("m_value", BindingFlags.Instance | BindingFlags.NonPublic);

object val = m_value.GetValue(field.GetValue(owner)).ToString();

This works fine and returns the proper value, but for m_inheritedBool I can't find how to make it work. Here's what I currently have:

FieldInfo field = owner.GetType().GetField(name, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);

Type type = field.FieldType;

while (type != typeof(DebugProperty<>))
{
    type = type.BaseType;

    if (type.IsGenericType)
        type = type.GetGenericTypeDefinition();
    
    if (type == null)
        break;
}

FieldInfo m_value = type.GetField("m_value", BindingFlags.Instance | BindingFlags.NonPublic);

object val = m_value.GetValue(field.GetValue(owner)).ToString();

This returns the proper m_value field, but when trying to get the value fails throwing the following error:

System.ArgumentException: Field m_value defined on type DebugProperty`1[T] is not a field on the target object which is of type Test+Bool.
Parameter name: obj

What object should I use to return the correct value?





Aucun commentaire:

Enregistrer un commentaire