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; + } } ///