public static object GetPropertyValue<TObject>(this PropertyInfo propertyInfo, TObject obj) where TObject : class
    {
        if (propertyInfo == null)
        {
            LoggerHandler.OnLogError("GetPropertyValue", new ArgumentNullException("propertyInfo null"));
            throw new ArgumentNullException("propertyInfo");
        }

        ParameterExpression parameterExpression = Expression.Parameter(typeof(TObject));
        return Expression.Lambda<Func<TObject, object>>(Expression.Convert(Expression.Property(Expression.Convert(parameterExpression, obj.GetType()), propertyInfo), typeof(object)), new ParameterExpression[1] { parameterExpression }).Compile()(obj);
    }
 public static void SetPropertyValue<TObject, TValue>(this PropertyInfo propertyInfo, TObject obj, TValue value)
    {
        if (propertyInfo == null)
        {
            LoggerHandler.OnLogError("SetPropertyValue", new ArgumentNullException("Property null"));
            throw new ArgumentNullException("propertyInfo");
        }

        if (propertyInfo.GetSetMethod() == null)
        {
            LoggerHandler.OnLogError("SetPropertyValue", new InvalidOperationException("Property does not have a setter"));
            throw new InvalidOperationException("Property does not have a setter");
        }

        ParameterExpression parameterExpression = Expression.Parameter(typeof(TObject));
        MemberExpression left = Expression.Property(Expression.Convert(parameterExpression, obj.GetType()), propertyInfo);
        ParameterExpression parameterExpression2 = Expression.Parameter(typeof(TValue));
        UnaryExpression right = Expression.Convert(parameterExpression2, propertyInfo.PropertyType);
        Expression.Lambda<Action<TObject, TValue>>(Expression.Assign(left, right), new ParameterExpression[2] { parameterExpression, parameterExpression2 }).Compile()(obj, value);
    }

标签: none

添加新评论