나는 그 속성이 해당 클래스에 존재하는지 확인 하기 위해 MemberExpression
's 를보고에서 찾을 수있는 일반 함수를 만들려고합니다 . 일반 속성에서는 잘 작동하지만 상속 된 속성에서는 찾지 못합니다.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
최신 정보:
@NetMage의 도움으로 방법을 수정할 수있었습니다. 내 메서드는 이제식이 다른 하위 클래스 일 T
수있는 반면 매개 변수가 다른 하위 클래스를 나타낼 수있는 경우도 다루고 있습니다.
var employeeObj = new Employee(); // here Employee is also inherited from Person class
trickyTest = IsPropertyPartOfClass<Student, string>(x => employeeObj.FirstName);
위의 예에서 함수가 false
.
public static bool IsPropertyPartOfClass<T, R>(Expression<Func<T, R>> expPropSel) {
MemberInfo mem_info_from_exp = ((MemberExpression)((LambdaExpression)expPropSel).Body).Member;
Type sourceType = ((MemberExpression)((LambdaExpression)expPropSel).Body).Expression.Type;
return typeof(T)
.GetProperties()
.Where(x=>
sourceType == typeof(T) &&
(
(x == mem_info_from_exp) ||
(
x.Name == mem_info_from_exp.Name &&
x.Module.Equals(mem_info_from_exp.Module) &&
x.MetadataToken == mem_info_from_exp.MetadataToken
)
)
)
.Any();
}
는 ReflectedType
사이에 다른 MemberInfo
람다과에서 PropertyInfo
아마도 사용한다 - 유형에서 s는 HasSameMetadataDefinitionAs
?
추가 된 이유는 여기 에서 설명을 참조하십시오 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다