From eb66061fa21bc474c62537c412eea86202d04c5c Mon Sep 17 00:00:00 2001
From: falcon <9504402@qq.com>
Date: Fri, 17 Feb 2023 14:57:47 +0800
Subject: [PATCH] =?UTF-8?q?=E4=B8=BAObject=E5=A2=9E=E5=8A=A0SetPropertyVal?=
=?UTF-8?q?ue=E6=96=B9=E6=B3=95=EF=BC=8C=E9=80=9A=E8=BF=87=E8=AF=A5?=
=?UTF-8?q?=E6=96=B9=E6=B3=95=E4=B8=BA=E5=AF=B9=E8=B1=A1=E7=9A=84=E6=AF=8F?=
=?UTF-8?q?=E4=B8=80=E4=B8=AA=E5=B1=9E=E6=80=A7=E8=AE=BE=E7=BD=AE=E5=80=BC?=
=?UTF-8?q?=E3=80=82=E4=B8=80=E8=88=AC=E7=94=A8=E5=9C=A8=E6=B5=8B=E8=AF=95?=
=?UTF-8?q?=E7=8E=AF=E5=A2=83=E4=B8=8B=E4=B8=BA=E6=8E=A5=E5=8F=A3=E5=AF=B9?=
=?UTF-8?q?=E8=B1=A1=E8=B5=8B=E5=80=BC?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
Falcon.SugarApi/ObjectExtend.cs | 55 +++++++++++++++++++++++++++++++++
1 file changed, 55 insertions(+)
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; }
+ }
+
}