I am trying to retrieve a value of private
property via reflection
// definition
public class Base
{
private bool Test { get { return true; } }
}
public class A: Base {}
public class B: Base {}
// now
object obj = new A(); // or new B()
// works
var test1 = typeof(Base).GetProperty("Test", BindingFlags.Instance | BindingFlags.NonPublic);
if(test1 != null) // it's not null
if((bool)test1.GetValue(obj, null)) // it's true
...
// doesn't works!
var test2 = obj.GetType().GetProperty("Test", BindingFlags.Instance | BindingFlags.NonPublic);
if(test2 != null) // is null !
...
Where is my mistake? I will need to use object
to pass instance, because some of private
properties will be declared in the A
or B
. And even hiding (with new
) Base
properties sometimes.
Test is private to Base. It is not visible to the inherited A/B classes. You should make it
protected
if you want it visible to the inheriting class.Or you can use
GetType().BaseType
if the inheritance tree is just one level.A
inherits fromBase
, so you need to tellGetProperty
to look for properties in the base class as well. Pass theFlattenHierarchy
flag as well: