增加类浅表复制方法

This commit is contained in:
falcon 2019-12-27 17:15:43 +08:00
parent 50eed23d1c
commit 705194cdad
3 changed files with 113 additions and 0 deletions

View File

@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Faclon.Extend
{
/// <summary>
/// 对象复制选项
/// </summary>
public class ObjectCopyToOption
{
/// <summary>
/// 获取默认值
/// </summary>
public static ObjectCopyToOption Default {
get {
return new ObjectCopyToOption();
}
}
}
}

View File

@ -0,0 +1,46 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace Faclon.Extend
{
/// <summary>
/// Object扩展
/// </summary>
public static class ObjectExtend
{
/// <summary>
/// 将当前对象属性赋值到目标对象属性中。
/// </summary>
/// <param name="source">当前对象</param>
/// <param name="target">目标属性</param>
/// <param name="option">复制选项</param>
public static void CopyTo(this object source,object target,ObjectCopyToOption option = null) {
if(source == null)
throw new ArgumentNullException(nameof(source));
if(target == null)
throw new ArgumentNullException(nameof(target));
option = option ?? ObjectCopyToOption.Default;
foreach(var ps in source.GetType().GetProperties()) {
if(ps.CanRead) {
var pt = target.GetType().GetProperty(ps.Name);
if(pt.CanWrite && ps.PropertyType.IsAssignableFrom(pt.PropertyType)) {
pt.SetValue(target,ps.GetValue(source,null),null);
}
}
}
}
/// <summary>
/// 根据提供的更新方法更新目标对象属性
/// </summary>
/// <typeparam name="TSource">原对象类型</typeparam>
/// <typeparam name="TTarget">目标对象类型</typeparam>
/// <param name="source">原对象</param>
/// <param name="target">目标对象</param>
/// <param name="action">转换方法</param>
public static void CopyTo<TSource, TTarget>(this TSource source,TTarget target,Action<TSource,TTarget> action) {
action(source,target);
}
}
}

View File

@ -0,0 +1,46 @@
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Faclon.Extend;
using System;
using System.Collections.Generic;
using System.Text;
namespace Faclon.Extend.Tests
{
[TestClass()]
public class ObjectExtendTests
{
[TestMethod()]
public void CopyToTest() {
var o1 = new Obj1 {
Id = 1,
Name = "Tom",
BirthDay = new DateTime(2019,8,5),
};
var o2 = new Obj2 {
BirthDay = DateTimeOffset.Parse("2019-8-5"),
};
//测试一般复制
o1.CopyTo(o2);
Assert.IsTrue(o2.Id == o1.Id,"int 复制错误");
Assert.IsTrue(o2.Name == o1.Name,"string 复制错误");
Assert.IsTrue(o2.BirthDay.Year == o1.BirthDay.Year,"DateTime到DateTimeOffset复制错误");
Assert.IsTrue(o2.BirthDay.Month == o1.BirthDay.Month,"DateTime到DateTimeOffset复制错误");
Assert.IsTrue(o2.BirthDay.Day == o1.BirthDay.Day,"DateTime到DateTimeOffset复制错误");
}
}
class Obj1
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime BirthDay { get; set; }
}
class Obj2
{
public int Id { get; set; }
public string Name { get; set; }
public DateTimeOffset BirthDay { get; set; }
}
}