我正在尝试创建一个通用函数,该函数可以通过查看MemberExpression
的Member
并在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
lambda的ReflectedType
与类型的MemberInfo
之间的PropertyInfo
不同-也许您应该使用HasSameMetadataDefinitionAs
?
请参阅讨论here,以了解为什么添加了它。
也许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));
}