修改了下clone方法

This commit is contained in:
FalconFly 2023-07-18 18:20:17 +08:00
parent 1918c13112
commit 606469692e

View File

@ -20,14 +20,15 @@ namespace Falcon.SugarApi
/// <typeparam name="TSource">原对象类型</typeparam> /// <typeparam name="TSource">原对象类型</typeparam>
/// <param name="source">原对象</param> /// <param name="source">原对象</param>
/// <param name="target">目标对象</param> /// <param name="target">目标对象</param>
public static TSource CloneTo<TSource>(this TSource source,[NotNull] object target) where TSource : class { /// <param name="ignoreCase">忽略大小写。默认false不忽略大小写</param>
public static TSource CloneTo<TSource>(this TSource source,[NotNull] object target,bool ignoreCase = false) where TSource : class {
_ = source ?? throw new ArgumentNullException(nameof(source)); _ = source ?? throw new ArgumentNullException(nameof(source));
_ = target ?? throw new ArgumentNullException(nameof(target)); _ = target ?? throw new ArgumentNullException(nameof(target));
var all = from s in source.GetType().GetProperties() var all = from s in source.GetType().GetProperties()
join t in target.GetType().GetProperties() on s.Name equals t.Name join t in target.GetType().GetProperties()
on ignoreCase ? s.Name.ToLower() : s.Name equals ignoreCase ? t.Name.ToLower() : t.Name
select new { s,t }; select new { s,t };
foreach(var item in all) { foreach(var item in all) {
//item.t.SetValue(target, Convert.ChangeType(item.s.getValue(source), item.t.Type));
item.t.SetValue(target,item.s.GetValue(source).ChangeType(item.t.PropertyType)); item.t.SetValue(target,item.s.GetValue(source).ChangeType(item.t.PropertyType));
} }
return source; return source;
@ -39,9 +40,10 @@ namespace Falcon.SugarApi
/// <typeparam name="Ttarget">目标对象类型</typeparam> /// <typeparam name="Ttarget">目标对象类型</typeparam>
/// <param name="target">目标对象</param> /// <param name="target">目标对象</param>
/// <param name="source">原对象</param> /// <param name="source">原对象</param>
/// <param name="ignoreCase">忽略大小写。默认false不忽略大小写</param>
/// <returns>目标对象</returns> /// <returns>目标对象</returns>
public static Ttarget CloneFrom<Ttarget>(this Ttarget target,object source) where Ttarget : class { public static Ttarget CloneFrom<Ttarget>(this Ttarget target,object source,bool ignoreCase = false) where Ttarget : class {
source.CloneTo(target); source.CloneTo(target,ignoreCase);
return target; return target;
} }