想要实现的效果:
xxxObj.Set(x=>x.Name, name)
如此,就可以实现:由业务方决定将 何值 写到 何属性 中。
关键代码
/// <summary>
/// 使用 lambda 表达式设置值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="target"></param>
/// <param name="memberLambda"></param>
/// <param name="value"></param>
public static void SetPropertyValue<T, TValue>(this T target, Expression<Func<T, TValue>> memberLambda, TValue value)
{
if (memberLambda.Body is MemberExpression memberSelectorExpression)
{
var property = memberSelectorExpression.Member as PropertyInfo;
if (property != null)
{
property.SetValue(target, value);
}
}
}
/// <summary>
/// 使用 lambda 表达式设置值
/// </summary>
/// <typeparam name="T"></typeparam>
/// <typeparam name="TValue"></typeparam>
/// <param name="target"></param>
/// <param name="memberLambda"></param>
/// <param name="default">没有获取到值时的默认值</param>
public static TValue GetPropertyValue<T, TValue>(this T target, Expression<Func<T, TValue>> memberLambda, TValue @default)
{
if (memberLambda.Body is MemberExpression memberSelectorExpression)
{
var property = memberSelectorExpression.Member as PropertyInfo;
if (property != null)
{
return (TValue)property.GetValue(target);
}
} return @default;
}
参考资料
c# - How to set property value using Expressions? - Stack Overflow