--
using System; using System.Reflection; namespace 深拷贝N2 { public static class ObjectCopier { /// <summary> /// 使用反射 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static T DeepCopyByReflect<T>(T obj) { //如果是字符串或值类型则直接返回 if (obj is string || obj.GetType().IsValueType) return obj; object retval = Activator.CreateInstance(obj.GetType()); FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); foreach (FieldInfo field in fields) { try { field.SetValue(retval, DeepCopyByReflect(field.GetValue(obj))); } catch { } } return (T)retval; } /// <summary> /// 跳过 List 属性字段 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <param name="skipList"></param> /// <returns></returns> public static T DeepCopyByReflect<T>(T obj, bool skipList) { //如果是字符串或值类型则直接返回 if (obj is string || obj.GetType().IsValueType) return obj; object retval = Activator.CreateInstance(obj.GetType()); FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static); foreach (FieldInfo field in fields) { try { if (skipList && field.FieldType.Name.Contains("List")) { continue; } field.SetValue(retval, DeepCopyByReflect(field.GetValue(obj), skipList)); } catch { } } return (T)retval; } } }
---