diff --git a/Falcon.SugarApi.Test/ObjectExtendTest.cs b/Falcon.SugarApi.Test/ObjectExtendTest.cs new file mode 100644 index 0000000..0eb318a --- /dev/null +++ b/Falcon.SugarApi.Test/ObjectExtendTest.cs @@ -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"; + } +} diff --git a/Falcon.SugarApi/ObjectExtend.cs b/Falcon.SugarApi/ObjectExtend.cs new file mode 100644 index 0000000..805881b --- /dev/null +++ b/Falcon.SugarApi/ObjectExtend.cs @@ -0,0 +1,42 @@ +using System; +using System.Diagnostics.CodeAnalysis; +using System.Linq; + +namespace Falcon.SugarApi +{ + /// + /// Object类型扩展方法 + /// + public static class ObjectExtend + { + /// + /// 对source进行浅表复制,并复制到target中 + /// + /// 原对象类型 + /// 原对象 + /// 目标对象 + public static TSource CloneTo(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; + } + + /// + /// 从原对象中浅表复制属性值 + /// + /// 目标对象类型 + /// 目标对象 + /// 原对象 + /// 目标对象 + public static Ttarget CloneFrom(this Ttarget target, object source) where Ttarget : class { + source.CloneTo(target); + return target; + } + } +}