How set value a property selector Expression>

前端 未结 6 673
野趣味
野趣味 2020-11-30 04:32

i need associate a entity property Address in my Person class entity with expressions linq in my FactoryEntities class using pattern factory idea, look this is what I have a

6条回答
  •  迷失自我
    2020-11-30 05:19

    This is my solution that uses Expression.Assign, but after looking more closely, the accepted answer is just as good.

    // optionally or additionally put in a class to capture the object type once
    // and then you don't have to repeat it if you have a lot of properties
    public Action GetSetter(
       Expression> pExpression
    ) {
       var parameter1 = Expression.Parameter(typeof(T));
       var parameter2 = Expression.Parameter(typeof(TProperty));
    
       // turning an expression body into a PropertyInfo is common enough
       // that it's a good idea to extract this to a reusable method
       var member = (MemberExpression)pExpression.Body;
       var propertyInfo = (PropertyInfo)member.Member;
    
       // use the PropertyInfo to make a property expression
       // for the first parameter (the object)
       var property = Expression.Property(parameter1, propertyInfo);
    
       // assignment expression that assigns the second parameter (value) to the property
       var assignment = Expression.Assign(property, parameter2);
    
       // then just build the lambda, which takes 2 parameters, and has the assignment
       // expression for its body
       var setter = Expression.Lambda>(
          assignment,
          parameter1,
          parameter2
       );
    
       return setter.Compile();
    }
    

    Another thing you can do is encapsulate them:

    public sealed class StrongProperty {
       readonly PropertyInfo mPropertyInfo;
    
       public string Name => mPropertyInfo.Name;
       public Func Get { get; }
       public Action Set { get; }
       // maybe other useful properties
    
       internal StrongProperty(
          PropertyInfo pPropertyInfo,
          Func pGet,
          Action pSet
       ) {
          mPropertyInfo = pPropertyInfo;
          Get = pGet;
          Set = pSet;
       }
    }
    

    And now you can pass these around, similar to delegates, and write code whose logic can vary by property. This gets around the fact that you can't pass properties by reference.

提交回复
热议问题