From 50b87ed420523c9f057c3b250591293bb994a05a Mon Sep 17 00:00:00 2001 From: FalconFly <12919280+falconfly@user.noreply.gitee.com> Date: Mon, 6 Nov 2023 12:02:10 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=BA=E5=AF=B9=E8=B1=A1=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E9=BB=98=E8=AE=A4=E6=B5=8B=E8=AF=95=E5=B1=9E=E6=80=A7=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- Falcon.SugarApi/ObjectExtend.cs | 35 +++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/Falcon.SugarApi/ObjectExtend.cs b/Falcon.SugarApi/ObjectExtend.cs index 0b215db..fec413f 100644 --- a/Falcon.SugarApi/ObjectExtend.cs +++ b/Falcon.SugarApi/ObjectExtend.cs @@ -173,6 +173,41 @@ namespace Falcon.SugarApi } return r; } + + /// + /// 为对象设置测试值。 + /// + /// 对象的类型 + /// 原始对象,可以为null + /// 可选,为目标对象复制 + /// 设置了测试值的对象 + public static T? ToTest(this T? source,Action? targetBuilder = null) where T : class, new() { + var type = typeof(T); + var typeName = type.FullName; + if(typeName.IsNullOrEmpty()) { + throw new Exception("typeof(T).FullName is null,can not createInstance!"); + } + var obj = type.Assembly.CreateInstance(typeName) as T ?? throw new Exception("创建目标对象失败!"); + foreach(PropertyInfo p in type.GetProperties()) { + if(!p.CanWrite || !p.CanRead) { + continue; + } + //如果属性为字符串 + if(p.PropertyType == typeof(string)) { + var val = source == null ? null : p.GetValue(source) as string; + if(val.IsNullOrEmpty()) { + p.SetValue(obj,p.Name); + } + else { + p.SetValue(obj,val); + } + continue; + } + //其他类型属性不做处理 + } + targetBuilder?.Invoke(obj); + return obj as T; + } } ///