找传奇、传世资源到传世资源站!

c# 对象拷贝属性 Copy方法

8.5玩家评分(1人评分)
下载后可评
介绍 评论 失效链接反馈

public object Copy(this object obj) { Object targetDeepCopyObj; Type targetType = obj.GetType(); //值类型 if (targetType.IsValueType == true) { targetDeepCopyObj = obj; } //引用类型 else { targetDeepCopyObj = System.Activator.CreateInstance(targetType); //创建引用对象 System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers(); foreach (System.Reflection.MemberInfo member in memberCollection) { if (member.MemberType == System.Reflection.MemberTypes.Field) { System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member; Object fieldValue = field.GetValue(obj); if (fieldValue is ICloneable) { field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone()); } else { field.SetValue(targetDeepCopyObj, Copy(fieldValue)); } } else if (member.MemberType == System.Reflection.MemberTypes.Property) { System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member; MethodInfo info = myProperty.GetSetMethod(false); if (info != null) { object propertyValue = myProperty.GetValue(obj, null); if (propertyValue is ICloneable) { myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null); } else { myProperty.SetValue(targetDeepCopyObj, Copy(propertyValue), null); } } } } } return targetDeepCopyObj; }

评论

发表评论必须先登陆, 您可以 登陆 或者 注册新账号 !


在线咨询: 问题反馈
客服QQ:174666394

有问题请留言,看到后及时答复