Skip to content

Commit

Permalink
增加CopyTo的其他用法,增加单元测试
Browse files Browse the repository at this point in the history
  • Loading branch information
j4587698 committed Oct 31, 2023
1 parent c4c20d9 commit 4b92377
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
10 changes: 10 additions & 0 deletions Jx.Toolbox.Test/ObjectTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,14 @@ public void SetPropertyTest()
Assert.Throws<InvalidOperationException>(() => { this.SetProperty("abc", 1);});
Assert.Throws<InvalidOperationException>(() => { this.SetProperty("ListTest", 1);});
}

[Fact]
public void CopyTest()
{
this.SetProperty(nameof(Test), "test");
this.SetProperty(nameof(IntTest), 1);
var obj = this.CopyTo<ObjectTest>();
Assert.Equal("test", obj.Test);
Assert.Equal(1, obj.IntTest);
}
}
13 changes: 13 additions & 0 deletions Jx.Toolbox/Extensions/ObjectExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,5 +88,18 @@ public static void CopyFrom<TSource, TTarget>(this TSource source, TTarget targe
{
CopyTo(target, source);
}

/// <summary>
/// 将源属性拷贝到目标
/// </summary>
/// <param name="source"></param>
/// <typeparam name="TTarget"></typeparam>
/// <returns></returns>
public static TTarget CopyTo<TTarget>(this object source)
{
var target = Activator.CreateInstance<TTarget>();
CopyTo(source, target);
return target;
}
}
}
2 changes: 1 addition & 1 deletion Jx.Toolbox/Jx.Toolbox.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
<PackageProjectUrl>https://github.com/j4587698/Jx.Toolbox</PackageProjectUrl>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
<PackageTags>tool</PackageTags>
<PackageVersion>0.3.5</PackageVersion>
<PackageVersion>0.3.6</PackageVersion>
</PropertyGroup>

</Project>

0 comments on commit 4b92377

Please sign in to comment.