Reputation:
I have following piece of code:
ClassName class = new ClassName();
var getValue = GetPrivateProperty<BaseClass>(class, "BoolProperty");
public static T GetPrivateProperty<T>(object obj, string name)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
PropertyInfo field = typeof(T).GetProperty(name, flags);
return (T)field.GetValue(obj, null);
}
Now when I get an InvalidCastException in the return statement that he can not convert the object with type System.Boolean to the type ClassName. BaseClass has the property. ClassName inherits from BaseClass. In have to access all properties from the "ClassName" Class. Since this property is private, I have to access it directly over the BaseClass. This works but I crashes because the property has the return value boolean.
Thanks!
Upvotes: 0
Views: 3163
Reputation: 3446
You got the property of type T
and the return value should also be of type T
? I don't believe that.
Maybe this will help:
var getValue = GetPrivateProperty<bool>(class, "BoolProperty");
public static T GetPrivateProperty<T>(object obj, string name)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
PropertyInfo field = null;
var objType = obj.GetType();
while (objType != null && field == null)
{
field = objType.GetProperty(name, flags);
objType = objType.BaseType;
}
return (T)field.GetValue(obj, null);
}
Please see the changes of <BaseClass>
to <bool>
and typeof(T).GetProperty
to obj.GetType().GetProperty
.
Upvotes: 1