如何检查继承的属性是否是类(子类)的一部分

问题描述 投票:0回答:2

我正在尝试创建一个通用函数,该函数可以通过查看MemberExpressionMember并在Type中找到它来判断该类中是否存在该属性。它对普通属性正常工作,但对于继承属性,找不到它们。

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();
}

输出:

Testing StudentID property
    Property is part of Class
Testing FirstName property
    Property is not part of Class
c# reflection linq-expressions
2个回答
0
投票

lambda的ReflectedType与类型的MemberInfo之间的PropertyInfo不同-也许您应该使用HasSameMetadataDefinitionAs

请参阅讨论here,以了解为什么添加了它。


0
投票

也许IsPropertyPartOfClass方法也可以检查基本属性

public static bool IsPropertyPartOfClass<T, R>(Expression<Func<T, R>> 
  expPropSel)
{
     MemberInfo memInfoFromExp = ((MemberExpression) expPropSel.Body).Member;
     var memberInfo = typeof(T).BaseType;
     return typeof(T).GetProperties().Any(x => x == memInfoFromExp || 
         memberInfo != null && memberInfo.GetProperties().Any(x => x == 
         memInfoFromExp));
}
© www.soinside.com 2019 - 2024. All rights reserved.