增加Object扩展方法CloneTo和CloneFrom方法可以将原对象属性浅表复制到目标对象

This commit is contained in:
falcon 2022-04-07 16:20:14 +08:00
parent ee3e44afb3
commit 520abc3454
2 changed files with 100 additions and 0 deletions

View File

@ -0,0 +1,58 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Falcon.SugarApi;
namespace Falcon.SugarApi.Test
{
[TestClass]
public class ObjectExtendTest
{
[TestMethod]
public void CloneToTest() {
var s = new SourceClass { };
var t = new TargetClass { };
t.ica.ItemA = "itemb";
Assert.IsTrue(t.ica.ItemA == "itemb");
var r = s.CloneTo(t);
Assert.IsNotNull(s);
Assert.IsNotNull(r);
Assert.IsNotNull(t);
Assert.IsTrue(s.ia == t.ia, $"a.id:{s.ia},t.ia:{t.ia}");
Assert.IsTrue(t.ia == 1);
Assert.IsTrue(s.sa == t.sa);
Assert.IsTrue(s.sc == "sc");
Assert.IsTrue(t.sd == "sd");
Assert.IsTrue(s.ica.ItemA == "itema");
Assert.IsTrue(t.ica.ItemA == "itema");
Assert.IsTrue(t.ica.Equals(s.ica));
}
}
public class SourceClass
{
public int ia { get; set; } = 1;
public string sa { get; set; } = "sa";
public string sc { get; set; } = "sc";
public ItemClass ica { get; set; } = new ItemClass();
}
public class TargetClass
{
public int ia { get; set; }
public string sa { get; set; }
public string sd { get; set; } = "sd";
public ItemClass ica { get; set; } = new ItemClass();
}
public class ItemClass
{
public string ItemA { get; set; } = "itema";
}
}

View File

@ -0,0 +1,42 @@
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
namespace Falcon.SugarApi
{
/// <summary>
/// Object类型扩展方法
/// </summary>
public static class ObjectExtend
{
/// <summary>
/// 对source进行浅表复制并复制到target中
/// </summary>
/// <typeparam name="TSource">原对象类型</typeparam>
/// <param name="source">原对象</param>
/// <param name="target">目标对象</param>
public static TSource CloneTo<TSource>(this TSource source, [NotNull] object target) where TSource : class {
_ = source ?? throw new ArgumentNullException(nameof(source));
_ = target ?? throw new ArgumentNullException(nameof(target));
var all = from s in source.GetType().GetProperties()
join t in target.GetType().GetProperties() on s.Name equals t.Name
select new { s, t };
foreach (var item in all) {
item.t.SetValue(target, Convert.ChangeType(item.s.GetValue(source), item.s.PropertyType));
}
return source;
}
/// <summary>
/// 从原对象中浅表复制属性值
/// </summary>
/// <typeparam name="Ttarget">目标对象类型</typeparam>
/// <param name="target">目标对象</param>
/// <param name="source">原对象</param>
/// <returns>目标对象</returns>
public static Ttarget CloneFrom<Ttarget>(this Ttarget target, object source) where Ttarget : class {
source.CloneTo(target);
return target;
}
}
}