Parent
class has only property Name
, Child
class inherits Parent
with no its own props.
PropertyInfo's for Parent.Name
and Child.Name
are different objects (very similar but still different).
There is a well-known way to obtain PropertyInfo having member expression, but it always returns PropertyInfo for parent object, not for child (see the code below).
Is there a way to get PropertyInfo object for Child.Name
having c => c.Name
on input and using MemberExpressions?
UPDATE: MemberInfo.HasSameMetadataDefinitionAs
returns true for Parent's and Child's Name property, but still wondering if I can make MemberExpression
return Child's PropertyInfo.
void Main()
{
// instantiate Parent and Child
var parent = new Parent();
var child = new Child();
// Get PropertyInfo's for the Name property of the parent and of the child
var parentNamePropertyInfo = (parent.GetType().GetProperty("Name"));
var childNamePropertyInfo = (child.GetType().GetProperty("Name"));
// see they are different
Debug.WriteLine($"same property info's? { parentNamePropertyInfo == childNamePropertyInfo}");
// Trying to get PropertyInfo of Child.Name but still having the one of the Parent.Name:
Expression<Func<Child, string>> expr = (p => p.Name);
MemberExpression member = expr.Body as MemberExpression;
PropertyInfo pi = (PropertyInfo)member.Member;
Debug.WriteLine(
pi == parentNamePropertyInfo ? "parent's info" :
pi == childNamePropertyInfo ? "childs's info" :
"None");
}
public class Parent
{
public string Name { get; set; }
}
public class Child : Parent
{
}
question from:
https://stackoverflow.com/questions/66050184/how-to-get-propertyinfo-of-the-property-inside-child-declared-in-parent-using-me 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…