diff --git a/Falcon.SugarApi/ObjectExtend.cs b/Falcon.SugarApi/ObjectExtend.cs index eadb356..a6053b9 100644 --- a/Falcon.SugarApi/ObjectExtend.cs +++ b/Falcon.SugarApi/ObjectExtend.cs @@ -104,6 +104,28 @@ namespace Falcon.SugarApi /// 要测试的对象 /// True表示对象不为null,否则为null public static bool IsNotNull([AllowNull] this object obj) => !obj.IsNull(); + + /// + /// 为对象属性设置属性值 + /// + /// 要设置的对象 + /// 通过属性和原始值获取新值的方法委托 + /// 设置属性值引发的异常 + public static T SetPropertyValue(this T obj,Func 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; + } } /// @@ -125,4 +147,37 @@ namespace Falcon.SugarApi public object? Value { get; set; } } + /// + /// 为目标属性设置值时引发的异常 + /// + public class ObjectSetValueException:Exception + { + /// + /// 为目标属性设置值时引发的异常 + /// + /// 目标对象 + /// 属性 + /// 目标属性值 + /// 内部异常 + public ObjectSetValueException(object? obj,PropertyInfo? info,object? val,Exception innExceprtion) + : base("为目标属性设置值时引发的异常",innExceprtion) { + this.Obj=obj; + this.Property=info; + this.Value=val; + } + + /// + /// 目标对象 + /// + public object? Obj { get; set; } + /// + /// 目标属性 + /// + public PropertyInfo? Property { get; set; } + /// + /// 目标属性值 + /// + public object? Value { get; set; } + } + }