반응형
속성 선택기 식>. 선택한 속성 값을 가져 오거나 설정하는 방법
이러한 방식으로 생성하려는 개체가 있습니다.
var foo = new FancyObject(customer, c=>c.Email); //customer has Email property
두 번째 매개 변수를 어떻게 선언해야합니까?
선택한 속성 setter / getter에 액세스하는 코드는 어떻게 생겼습니까?
업데이트되었습니다. Email 속성이있는 모델에는 여러 엔터티가 있습니다. 따라서 서명은 다음과 같습니다.
public FancyObject(Entity holder, Expression<Func<T>> selector)
및 생성자 호출
var foo = new FancyObject(customer, ()=>customer.Email);
매개 변수는 Expression<Func<Customer,string>> selector
. 플랫 컴파일을 통해 읽을 수 있습니다.
Func<Customer,string> func = selector.Compile();
그런 다음 액세스 할 수 있습니다 func(customer)
. 할당은 더 까다 롭습니다. 간단한 선택 자의 경우 다음과 같이 간단히 분해 할 수 있기를 바랄 수 있습니다.
var prop = (PropertyInfo)((MemberExpression)selector.Body).Member;
prop.SetValue(customer, newValue, null);
그러나 더 복잡한 표현식은 수동 트리 워크 또는 4.0 표현식 노드 유형 중 일부가 필요합니다.
Expression<Func<Customer, string>> email
= cust => cust.Email;
var newValue = Expression.Parameter(email.Body.Type);
var assign = Expression.Lambda<Action<Customer, string>>(
Expression.Assign(email.Body, newValue),
email.Parameters[0], newValue);
var getter = email.Compile();
var setter = assign.Compile();
유형은 소스와 결과라는 두 가지 유형 매개 변수를 사용하여 제네릭이어야합니다. 예를 들어 다음을 사용할 수 있습니다.
var foo = new FancyObject<Customer, string>(customer, c => c.Email);
첫 번째 매개 변수는 유형 TSource
이고 두 번째 매개 변수는 다음 과 Expression<Func<TSource, TResult>>
같습니다.
public class FancyObject<TSource, TResult>
{
private readonly TSource value;
private readonly Expression<Func<TSource, TResult>> projection;
public FancyObject(TSource value,
Expression<Func<TSource, TResult>> projection)
{
this.value = value;
this.projection = projection;
}
}
제네릭이 아닌 유형의 정적 메서드와 함께 사용하기 더 간단하게 만들 수 있습니다.
var foo = FancyObject.Create(customer, c => c.Email);
유형 추론을 사용하여 유형 인수를 해결할 수 있습니다.
반응형
'UFO ET IT' 카테고리의 다른 글
File.ReadAllLines ()와 File.ReadAllText ()의 차이점은 무엇입니까? (0) | 2020.11.27 |
---|---|
Excel 워크 시트의 이름 길이에 제한이 있습니까? (0) | 2020.11.27 |
Ubuntu 10.10 (Maverick Meerkat)에서 직렬 -USB 장치에 터미널을 연결하려면 어떻게해야합니까? (0) | 2020.11.27 |
JQuery Mobile Fixed Toolbar 및 Footer Bar가 사라집니다. (0) | 2020.11.26 |
Java에서 SortedMap 인터페이스를 사용하는 방법은 무엇입니까? (0) | 2020.11.26 |