封装示例
public static class ObjectExtensions
{
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);
}
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