There are two things to know about.
(1) When using:
this.GetType()
or equivalently just GetType()
, the return type is the actual runtime type of the actual instance. Since _Default
is a non-printable class, this type may well be more derived (more specialized type) than _Default
, that is, some class that has _Default
as its direct or indirect base class.
If you always want the "persistent" type _Default
, use the typeof
keyword, so use:
typeof(_Default)
instead of GetType()
. This alone will solve your problem.
(2) Even if you specify BindingFlags.NonPublic
, inherited private
members will not be returned. With your choice, binding flags return private
methods declared in the same class (derived class), but private
methods inherited from base classes are not returned. However, with members, internal
and protected
returned as those declared in the class itself, and those declared in the base classes.
This may make sense, since the private
method is not intended to be called from a derived class.
Change the access level of your DynamicHandler
method from private
to, for example. protected
(as suggested in another answer) would be enough to solve your problem, since inherited protected members are selected using BindingFlags.NonPublic
.
It is still interesting that you cannot get inherited private
members with BindingFlags
. Related topic C #: accessing inherited private members of an instance through reflection . You can write a method that looks for all the basic types, of course, for example:
static MethodInfo GetPrivateMethod(Type type, string name) { MethodInfo retVal; do { retVal = type.GetMethod(name, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); if (retVal != (object)null) break; type = type.BaseType; } while (type != (object)null); return retVal; }
That alone would also solve your problem.