为Object增加SetPropertyValue方法,通过该方法为对象的每一个属性设置值。一般用在测试环境下为接口对象赋值

This commit is contained in:
falcon 2023-02-17 14:57:47 +08:00
parent ee4854787e
commit eb66061fa2

View File

@ -104,6 +104,28 @@ namespace Falcon.SugarApi
/// <param name="obj">要测试的对象</param> /// <param name="obj">要测试的对象</param>
/// <returns>True表示对象不为null否则为null</returns> /// <returns>True表示对象不为null否则为null</returns>
public static bool IsNotNull([AllowNull] this object obj) => !obj.IsNull(); public static bool IsNotNull([AllowNull] this object obj) => !obj.IsNull();
/// <summary>
/// 为对象属性设置属性值
/// </summary>
/// <param name="obj">要设置的对象</param>
/// <param name="GetValue">通过属性和原始值获取新值的方法委托</param>
/// <exception cref="ObjectSetValueException">设置属性值引发的异常</exception>
public static T SetPropertyValue<T>(this T obj,Func<PropertyInfo,object?,object?> GetValue) where T : class {
foreach(PropertyInfo info in obj.GetType().GetProperties()) {
if(info.CanWrite&&info.CanRead) {
object? originalVal = info.GetValue(obj);
var val = GetValue(info,originalVal);
try {
info.SetValue(obj,val);
}
catch(Exception ex) {
throw new ObjectSetValueException(obj,info,val,ex);
}
}
}
return obj;
}
} }
/// <summary> /// <summary>
@ -125,4 +147,37 @@ namespace Falcon.SugarApi
public object? Value { get; set; } public object? Value { get; set; }
} }
/// <summary>
/// 为目标属性设置值时引发的异常
/// </summary>
public class ObjectSetValueException:Exception
{
/// <summary>
/// 为目标属性设置值时引发的异常
/// </summary>
/// <param name="obj">目标对象</param>
/// <param name="info">属性</param>
/// <param name="val">目标属性值</param>
/// <param name="innExceprtion">内部异常</param>
public ObjectSetValueException(object? obj,PropertyInfo? info,object? val,Exception innExceprtion)
: base("为目标属性设置值时引发的异常",innExceprtion) {
this.Obj=obj;
this.Property=info;
this.Value=val;
}
/// <summary>
/// 目标对象
/// </summary>
public object? Obj { get; set; }
/// <summary>
/// 目标属性
/// </summary>
public PropertyInfo? Property { get; set; }
/// <summary>
/// 目标属性值
/// </summary>
public object? Value { get; set; }
}
} }