jeudi 12 décembre 2019

How to check if inherited property is the part of class (sub-class)

I am trying to create a generic function that can tell by looking in the MemberExpression's Member and finding it in a Type to see if that property exists in that class. It works fine with normal properties but with inherited properties it does not find them.

class Person {
    public string FirstName {get;set;}
    public string LastName {get;set;}       
}

class Student : Person {
    public string StudentID {get;set;}
}

public static void Main()
{
    bool test1 = IsPropertyPartOfClass<Student, string>(x => x.StudentID);
    Console.WriteLine("Testing StudentID property");
    if (test1)
        Console.WriteLine("\tProperty is part of Class");
    else
        Console.WriteLine("\tProperty is not part of Class");

    bool test2 = IsPropertyPartOfClass<Student, string>(x => x.FirstName);
    Console.WriteLine("Testing FirstName property");
    if (test2)
        Console.WriteLine("\tProperty is part of Class");
    else
        Console.WriteLine("\tProperty is not part of Class");
}

public static bool IsPropertyPartOfClass<T, R>(Expression<Func<T, R>> expPropSel){
    MemberInfo mem_info_from_exp = ((MemberExpression)((LambdaExpression)expPropSel).Body).Member;
    return typeof(T).GetProperties().Where(x=> x == mem_info_from_exp).Any();
}

Output:

Testing StudentID property
    Property is part of Class
Testing FirstName property
    Property is not part of Class




Aucun commentaire:

Enregistrer un commentaire