Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
726 views
in Technique[技术] by (71.8m points)

c# - How to get PropertyInfo of the property inside child declared in parent using MemberExpression?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...