Loading

[笔记] C# 使用 lambda 表达式进行对象的值获取与赋值

想要实现的效果:

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

原文链接:https://www.cnblogs.com/jasongrass/p/14150518.html

posted @ 2020-12-17 16:50  J.晒太阳的猫  阅读(1839)  评论(0编辑  收藏  举报