封装示例

public static class ObjectExtensions
{
    /// <summary>
    /// 动态获取对象属性的值
    /// </summary>
    /// <typeparam name="T">目标对象类型</typeparam>
    /// <param name="o">目标对象</param>
    /// <param name="propertyName">属性名</param>
    /// <returns></returns>
    public static object GetPropertyValue<T>(this T o, string propertyName)
    {
        if (o == null)
        {
            return null;
        }

        Type type = o.GetType();
        PropertyInfo property = type.GetProperty(propertyName);
        if (property == null || property.GetGetMethod() == null)
        {
            return null;
        }
        var getValue = (Func<T, object>)Delegate.CreateDelegate(typeof(Func<T, object>), property.GetGetMethod());
        return getValue(o);
    }

    /// <summary>
    /// 动态设置对象属性的值
    /// </summary>
    /// <typeparam name="T">属性值的类型</typeparam>
    /// <param name="o">目标对象</param>
    /// <param name="propertyName">属性名</param>
    /// <param name="value">属性值</param>
    public static void SetPropertyValue<T>(this object o, string propertyName, T value)
    {
        if (o == null)
        {
            return;
        }

        Type type = o.GetType();
        PropertyInfo property = type.GetProperty(propertyName);
        if (property == null || property.GetSetMethod() == null)
        {
            return;
        }
        var setValue = (Action<T>)Delegate.CreateDelegate(typeof(Action<T>), o, property.GetSetMethod());
        setValue(value);
    }
}
csharp