我正在尝试创建一个通用函数,该函数可以通过查看MemberExpression
的{{1}}并在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();
}
更新:
借助@NetMage,我可以修改我的方法。请注意,我的方法现在还涵盖了表达式可能属于不同子类而Testing StudentID property
Property is part of Class
Testing FirstName property
Property is not part of Class
参数可能代表不同子类的情况。
T
在上面的示例中,我们希望函数返回var employeeObj = new Employee(); // here Employee is also inherited from Person class
trickyTest = IsPropertyPartOfClass<Student, string>(x => employeeObj.FirstName);
。
false
答案 0 :(得分:0)
lambda的s
和类型的ReflectedType
之间的MemberInfo
不同-也许您应该使用PropertyInfo
?
请参阅讨论here,了解其添加原因。
答案 1 :(得分: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));
}