C#反射复制实体
通過反射,深度復(fù)制實體的副本
public static T Clone<T>(T obj){Type type = obj.GetType();//對于沒有公共無參構(gòu)造函數(shù)的類型此處會報錯T returnObj = (T)Activator.CreateInstance(type);FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);if (fields!=null && fields.Length>0){for (int i = 0; i < fields.Length; i++){FieldInfo field = fields[i];var fieldValue = field.GetValue(obj);///值類型,字符串,枚舉類型直接把值復(fù)制,不存在淺拷貝if (fieldValue.GetType().IsValueType || fieldValue.GetType().Equals(typeof(System.String)) || fieldValue.GetType().IsEnum){field.SetValue(returnObj, fieldValue);}else{field.SetValue(returnObj, Clone(fieldValue));}}}//屬性PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);if (properties!=null && properties.Length>0){for (int i = 0; i < properties.Length; i++){PropertyInfo property = properties[i];var propertyValue = property.GetValue(obj);if (propertyValue.GetType().IsValueType || propertyValue.GetType().Equals(typeof(System.String)) || propertyValue.GetType().IsEnum){property.SetValue(returnObj, propertyValue);}else{property.SetValue(returnObj, Clone(propertyValue));}}}return returnObj;}總結(jié)
- 上一篇: SQL Server 创建存储过程
- 下一篇: 店宝宝电脑版_用店宝宝是为了什么?客服全