Reflecting a private field from a base class

Viewed 33634

Here is the structure:

MyClass : SuperClass2

SuperClass2 : SuperClass1

superClass2 is in Product.Web and SuperClass1 is in the .NET System.Web assembly

I'm trying to force a value into a private bool field on SuperClass1. But not matter what I try I cannot get the fields to come back from reflection.

I'm using the following code with different BindingFlag combinations but nothing has worked so far. SuperClass1 is an abstract class.

((SuperClass1)this).GetType().GetFields(System.Reflection.BindingFlags.NonPublic);

Notes: When I use GetProperties() I get back a nice big list but when I specify any bindingflags I get nothing even though there are matching properties. Whats the deal?

Also, the field is not marked internal

Obvisouly I would be using GetField(string name, BindingFlags) but I can't even get GetFlags() to work.

Update: I've tried adding BindingFlags.Instance as suggested but it doesn't work (as expected anyway). I get back 2 fields that are coming from the class SuperClass1 inherits from. Returns null when used with GetField(string name, Flags)

Here is the code for the base class I'm trying to get the field for

public abstract class BaseValidator : Label, IValidator
  {
    private bool propertiesChecked;
...
}
5 Answers

Extension method:

/// <summary>
/// Returns the FieldInfo matching 'name' from either type 't' itself or its most-derived 
/// base type (unlike 'System.Type.GetField'). Returns null if no match is found.
/// </summary>
public static FieldInfo GetPrivateField(this Type t, String name)
{
    const BindingFlags bf = BindingFlags.Instance | 
                            BindingFlags.NonPublic | 
                            BindingFlags.DeclaredOnly;

    FieldInfo fi;
    while ((fi = t.GetField(name, bf)) == null && (t = t.BaseType) != null)
        ;
    return fi;
}
Related