C#对象深拷贝

C#对象深拷贝

 

 

众所周知,c#中的对象存在值类型和引用类型之分,故而对象之间的赋值就存在浅拷贝和深拷贝的概念

网上的深拷贝方法也很多,但是要么写的无比复杂,要么有诸多限制

最终还是选择了反射的方法,虽然都说反射效率太低,但是它毕竟最常见最通用的方法

复制代码
public static T DeepCopy<T>(T obj)
        {
            //如果是字符串或值类型则直接返回
            if (obj==null||obj is string || obj.GetType().IsValueType) return obj;

            object retval = Activator.CreateInstance(obj.GetType());
            System.Reflection.FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
            foreach (System.Reflection.FieldInfo field in fields)
            {
                try { field.SetValue(retval, DeepCopy(field.GetValue(obj))); }
                catch { }
            }
            return (T)retval;
        }
复制代码

 

 

 

 

 

if (!hasdata.Any())
{
decimal Total = 0, T1000 = 0, T500 = 0, T100 = 0;
string[] arrtmps = { "Total", "T1000", "T500", "T100" };

if (Request["Total"].ToDecimal() != 0 || Request["T1000"].ToDecimal() != 0 || Request["T500"].ToDecimal() != 0 || Request["T100"].ToDecimal() != 0)
{
foreach (var item in arrtmps)
{
Decimal tpdec = Request[item].ToDecimal();
if (tpdec != 0)
{
var colltmp = DeepCopy<ClrMoneyBalance>(collection);
colltmp.UseMoney = tpdec;
colltmp.BalanceMoney = tpdec;
colltmp.Denom = item == "Total" ? -1 : item == "T1000" ? 1000 : item == "T500" ? 500 : 100;
_iClrMoneyBalanceService.Save(id, colltmp);
}
}
_unitOfWork.Commit();
return RedirectToAction("Index");
}
else
{
SetDefault(id, collection);
ModelState.AddModelError("Denom", "Total 1000 500 100 field is required. ");
return View(collection);

}
}

 

 

 

 //Id 排除

public T DeepCopy<T>(T obj)
{
//如果是字符串或值类型则直接返回
if (obj == null || obj is string || obj.GetType().IsValueType) return obj;

object retval = Activator.CreateInstance(obj.GetType());
System.Reflection.PropertyInfo[] fields = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
PropertyInfo pid = obj.GetType().GetProperty("Id");
foreach (System.Reflection.PropertyInfo field in fields)
{
if (field != pid)
{
try { field.SetValue(retval, DeepCopy(field.GetValue(obj))); }
catch { }
}

}
return (T)retval;
}

 

 

posted @ 2019-01-25 16:04  ~雨落忧伤~  阅读(996)  评论(0编辑  收藏  举报