diff --git a/Jx.Toolbox/Extensions/ObjectExtension.cs b/Jx.Toolbox/Extensions/ObjectExtension.cs index 9e9db1e..730b7aa 100644 --- a/Jx.Toolbox/Extensions/ObjectExtension.cs +++ b/Jx.Toolbox/Extensions/ObjectExtension.cs @@ -55,5 +55,38 @@ public static void SetProperty(this object obj, string name, object value, Bindi } } } + + /// + /// 将源属性拷贝到目标 + /// + /// + /// + /// + /// + public static void CopyTo(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); + } + } + } + + /// + /// 将目标属性拷贝到源 + /// + /// + /// + /// + /// + public static void CopyFrom(this TSource source, TTarget target) + { + CopyTo(target, source); + } } } \ No newline at end of file diff --git a/Jx.Toolbox/Jx.Toolbox.csproj b/Jx.Toolbox/Jx.Toolbox.csproj index 611d249..bcce7ca 100644 --- a/Jx.Toolbox/Jx.Toolbox.csproj +++ b/Jx.Toolbox/Jx.Toolbox.csproj @@ -9,7 +9,7 @@ https://github.com/j4587698/Jx.Toolbox MIT tool - 0.3.3 + 0.3.4 diff --git a/README.md b/README.md index 9d9a842..64cc9e8 100644 --- a/README.md +++ b/README.md @@ -80,6 +80,8 @@ ObjectExtension ``` 任意类型.GetProperties(属性类型); // 获取所有属性,默认获取public的属性 任意类型.SetProperty("属性名", 属性值, 属性类型); // 使用反射给实例赋值,默认只查找public的属性 +任意类型.CopyTo(实例); // 使用反射将公开的实例属性复制到实例的同名属性中 +任意类型.CopyFrom(实例); // 使用方式将实例的公开的实例属性复制到源的同名属性中 ``` EnumExtension