110,568
社区成员
发帖
与我相关
我的任务
分享
/// <summary>
/// 类之间深拷贝
/// </summary>
/// <param name="obj">源型类对象</param>
/// <returns></returns>
public static object CopyObject(this object obj)
{
Object targetDeepCopyObj = null;
//需判断是否为Null
if (obj == null) return 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, CopyObject(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, CopyObject(propertyValue), null);
}
}
}
}
}
return targetDeepCopyObj;
}
public class User
{
public int id { get; set; }
public virtual string name { get; set; }
public virtual string buyer { get; set; }
public virtual string idArr { get; set; }
public User Copy()
{
return (User)this.MemberwiseClone();
}
}
static void Main(string[] args)
{
User u = new User() { id=1};
User u1 = u;
u1.id = 2;
Console.WriteLine(u.id); //u的id=2 变化了
User u2 = u.Copy();
u2.id = 3;
Console.WriteLine(u.id); //u的id=2 没有变化
Console.ReadLine();
}