Skip to content

Commit

Permalink
Merge pull request #9 from j4587698/dev-obj
Browse files Browse the repository at this point in the history
增加CopyFrom CopyTo
  • Loading branch information
j4587698 authored May 18, 2023
2 parents 9ce7182 + c708e6c commit ac304fd
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
33 changes: 33 additions & 0 deletions Jx.Toolbox/Extensions/ObjectExtension.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,5 +55,38 @@ public static void SetProperty(this object obj, string name, object value, Bindi
}
}
}

/// <summary>
/// 将源属性拷贝到目标
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TTarget"></typeparam>
public static void CopyTo<TSource, TTarget>(this TSource source, TTarget target)
{
PropertyInfo[] propertyInfos = GetProperties(source, BindingFlags.Public | BindingFlags.Instance);
Type targetType = target.GetType();
foreach (var propertyInfo in propertyInfos)
{
object value = propertyInfo.GetValue(source, null);
if (value != null)
{
targetType.GetProperty(propertyInfo.Name)?.SetValue(target, value, null);
}
}
}

/// <summary>
/// 将目标属性拷贝到源
/// </summary>
/// <param name="source"></param>
/// <param name="target"></param>
/// <typeparam name="TSource"></typeparam>
/// <typeparam name="TTarget"></typeparam>
public static void CopyFrom<TSource, TTarget>(this TSource source, TTarget target)
{
CopyTo(target, source);
}
}
}
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.3</PackageVersion>
<PackageVersion>0.3.4</PackageVersion>
</PropertyGroup>

</Project>
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,8 @@ ObjectExtension
```
任意类型.GetProperties(属性类型); // 获取所有属性,默认获取public的属性
任意类型.SetProperty("属性名", 属性值, 属性类型); // 使用反射给实例赋值,默认只查找public的属性
任意类型.CopyTo(实例); // 使用反射将公开的实例属性复制到实例的同名属性中
任意类型.CopyFrom(实例); // 使用方式将实例的公开的实例属性复制到源的同名属性中
```

EnumExtension
Expand Down

0 comments on commit ac304fd

Please sign in to comment.