Here is my method:
public static MethodCallExpression ClonePropertyAssignmentLambda<T>(Expression source, string property)
{
var targetExp = Expression.Parameter(typeof (T), "target");
var propertyInfo = typeof (T).Get开发者_JS百科Property(property);
var targetProperty = Expression.Property(targetExp, propertyInfo);
var sourceProperty = Expression.Property(source, propertyInfo);
return Expression.Call(targetProperty, ((PropertyInfo) targetProperty.Member).GetSetMethod(), sourceProperty);
}
Here is how I'm calling it:
ClonePropertyAssignmentLambda<Person>(source, "Name")
I'm getting the error on the Expression.Call line. I get a similar error if I call GetGetMethod.
You're trying to get the Name
property of a string
object.
Change it to
return Expression.Call(targetExp, propertyInfo.GetSetMethod(), sourceProperty);
Never mind, I figured it out like 2 seconds after posting. Why do I always do that?
The first param for Expression.Call should be targetExp.
精彩评论