UFO ET IT

식을 사용하여 속성 값을 설정하는 방법은 무엇입니까?

ufoet 2020. 12. 7. 21:17
반응형

식을 사용하여 속성 값을 설정하는 방법은 무엇입니까?


이 질문에 이미 답변이 있습니다.

다음과 같은 방법이 주어집니다.

public static void SetPropertyValue(object target, string propName, object value)
{
    var propInfo = target.GetType().GetProperty(propName,
                         BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);

    if (propInfo == null)
        throw new ArgumentOutOfRangeException("propName", "Property not found on target");
    else
        propInfo.SetValue(target, value, null);
}

target에 대한 추가 매개 변수를 전달할 필요없이 표현식이 활성화 된 동등 물을 작성하는 방법은 무엇입니까?

속성을 직접 설정하는 대신 왜 이렇게 하는가? 예를 들어 공용 getter가 있지만 개인 setter가있는 속성이있는 다음 클래스가 있다고 가정합니다.

public class Customer 
{
   public string Title {get; private set;}
   public string Name {get; set;}
}

다음과 같이 전화를 걸고 싶습니다.

var myCustomerInstance = new Customer();
SetPropertyValue<Customer>(cust => myCustomerInstance.Title, "Mr");

이제 몇 가지 샘플 코드가 있습니다.

public static void SetPropertyValue<T>(Expression<Func<T, Object>> memberLamda , object value)
{
    MemberExpression memberSelectorExpression;
    var selectorExpression = memberLamda.Body;
    var castExpression = selectorExpression as UnaryExpression;

    if (castExpression != null)
        memberSelectorExpression = castExpression.Operand as MemberExpression;
    else
        memberSelectorExpression = memberLamda.Body as MemberExpression;

    // How do I get the value of myCustomerInstance so that I can invoke SetValue passing it in as a param? Is it possible

}

포인터가 있습니까?


확장 방법으로 속임수를 쓰고 삶을 더 편하게 만들 수 있습니다.

public static class LambdaExtensions
{
    public static void SetPropertyValue<T, TValue>(this T target, Expression<Func<T, TValue>> memberLamda, TValue value)
    {
        var memberSelectorExpression = memberLamda.Body as MemberExpression;
        if (memberSelectorExpression != null)
        {
            var property = memberSelectorExpression.Member as PropertyInfo;
            if (property != null)
            {
                property.SetValue(target, value, null);
            }
        }
    }
}

그리고:

var myCustomerInstance = new Customer();
myCustomerInstance.SetPropertyValue(c => c.Title, "Mr");

The reason why this is easier is because you already have the target on which the extension method is invoked. Also the lambda expression is a simple member expression without closures. In your original example the target is captured in a closure and it could be a bit tricky to get to the underlying target and PropertyInfo.

참고URL : https://stackoverflow.com/questions/9601707/how-to-set-property-value-using-expressions

반응형