Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master'
Browse files Browse the repository at this point in the history
  • Loading branch information
j4587698 committed Sep 13, 2023
2 parents a7c2211 + ac304fd commit 558fe08
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
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: 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 558fe08

Please sign in to comment.