당신은 컴파일 시간 속성 참조를 해결하기 위해 람다 표현식을 사용할 수 있습니다 의존, 일명 두 가지 일반적인 유형되기 위해이 방법을 추가하지 않고 그것을 할 우아한 방법이 있나요. (Retrieving Property name from lambda expression에서 수정 된 코드)
public PropertyInfo GetPropertyInfo<TProperty>(
Expression<Func<TProperty>> propertyLambda)
{
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
return propInfo;
}
소스 개체 인스턴스를 갖는 쓰기를 제외하고 필요가 없습니다 당신이 그것을 적용 할 경우 이을 할 수 있지만,하지만 당신은 (확장 방법으로 그것을 사용할 필요가 없습니다 라인)
public class Test
{
public string Prop { get; set; }
}
Test t = new Test();
PropertyInfo propInfo = GetPropertyInfo(() => t.Prop);
Console.WriteLine(propInfo.Name + " -> " + propInfo.PropertyType); //Prop -> System.String
편집 :
public static class TypedReflection<TSource>
{
public static PropertyInfo GetPropertyInfo<TProperty>(
Expression<Func<TSource, TProperty>> propertyLambda)
{
MemberExpression member = propertyLambda.Body as MemberExpression;
if (member == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
PropertyInfo propInfo = member.Member as PropertyInfo;
if (propInfo == null)
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
return propInfo;
}
}
,369 : 당신은 몇 가지 좋은 구문을 갖고 싶어하고 형식의 개체에 대한 기존의 참조를 피하기해야하는 경우처럼 뭔가를 할 수
그리고 원하는 전화 : 추가적인 입력 된 반사 방법을 추가하는 아주 쉽게,이 시점에서
PropertyInfo propInfo = TypedReflection<Test>.GetPropertyInfo(o => o.Prop);
EDIT (메소드, 필드 등을 얻을 수) : 그것은 여전히 그렇다고 두 가지 일반적인 유형의 의존의 , 형식 유추를 통해 숨겨져 있습니다. 나는 두 번째 예제를 선호한다. 최소한 클래스 선언 유형을 지정해야합니다 (유형 안전성이 필요하기 때문에).하지만 오브젝트 인스턴스는 필요하지 않습니다. 또한 속성의 이름을 바꾸면이 코드로 전파되어 PropertyInfo
을 얻는 이점이 있습니다.
http://blog.slaks.net/2010/12/partial -type-inference-in-net.html – SLaks