using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
namespace HuaTong.General.Utility
{
/// <summary>
/// 实体处理工具类
/// </summary>
public static class ModelHandler
{ /// <summary>
/// Determine of specified type is nullable
/// </summary>
public static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
} /// <summary>
/// Return underlying type if type is Nullable otherwise return the type
/// </summary>
public static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType)
{
return t;
}
else
{
return Nullable.GetUnderlyingType(t);
}
}
else
{
return t;
}
} public static 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;
} public static T CloneEntity<T>(this T entity) where T : new()
{
T ent = new T();
PropertyInfo[] propertyInfoes = PropCache<T>();
foreach (PropertyInfo propertyInfo in propertyInfoes)
{
if (propertyInfo.PropertyType.IsArray || (propertyInfo.PropertyType.IsClass && propertyInfo.PropertyType != typeof(string)))
{
object child = propertyInfo.GetValue(entity, null);
if (child == null)
continue;
Type childType = child.GetType();
if (childType.IsGenericType)
{ Type typeDefinition = childType.GetGenericArguments()[];
IList items = childType.Assembly.CreateInstance(childType.FullName) as IList; PropertyInfo[] childPropertyInfoes = PropCache(typeDefinition);
IList lst = child as IList;
for (int i = ; i < lst.Count; i++)
{
object itemEntity = null;
if (typeDefinition.IsClass && typeDefinition != typeof(string))
{
itemEntity = typeDefinition.Assembly.CreateInstance(typeDefinition.FullName);
foreach (PropertyInfo childProperty in childPropertyInfoes)
{
childProperty.SetValue(itemEntity, childProperty.GetValue(lst[i], null), null);
}
}
else
{
itemEntity = lst[i];
} items.Add(itemEntity);
}
propertyInfo.SetValue(ent, items, null); }
continue;
}
propertyInfo.SetValue(ent, propertyInfo.GetValue(entity, null), null);
} FieldInfo[] fieldInfoes = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo fieldInfo in fieldInfoes)
{
fieldInfo.SetValue(ent, fieldInfo.GetValue(entity));
} return ent;
} /// <summary>
/// 复制实体的属性至另一个类实体的同名属性(属性不区分大小写),被复制的值必须支持隐式转换
/// </summary>
public static T1 CopyEntity<T1, T2>(T1 copyTo, T2 from, string replace_copy = null, string replace_from = null)
where T1 : class, new()
where T2 : class, new()
{
var prop1 = ModelHandler.PropCache<T1>();
var prop2 = ModelHandler.PropCache<T2>(); foreach (var p1 in prop1)
{
var fname = replace_copy != null ? Regex.Replace(p1.Name, replace_copy, "") : p1.Name; //同名属性不区分大小写
var p2 = prop2.SingleOrDefault(
m => replace_from != null
? StringHelper.IsEqualString(Regex.Replace(m.Name, replace_from, ""), fname)
: StringHelper.IsEqualString(m.Name, fname));
if (p2 != null)
{
var p2value = p2.GetValue(from, null);
//忽略空值
if (p2value != null && p2value != DBNull.Value)
{
//是否Nullable
if (p1.PropertyType.IsGenericType &&
p1.PropertyType.GetGenericTypeDefinition().Equals(typeof (Nullable<>)))
{
//Nullable数据转换
NullableConverter converter = new NullableConverter(p1.PropertyType);
p1.SetValue(copyTo, converter.ConvertFrom(p2value.ToString()), null);
}
else
{
p1.SetValue(copyTo, Convert.ChangeType(p2value, p1.PropertyType), null);
}
}
else if (p2.PropertyType == typeof (string))
{
//字符串添加默认值string.Empty
p1.SetValue(copyTo, string.Empty, null);
}
}
}
return copyTo;
} /// <summary>
/// 复制实体集合
/// </summary>
public static List<T1> CopyEntityList<T1, T2>(List<T1> copyTo, List<T2> from)
where T1 : class, new()
where T2 : class, new()
{
foreach (var f in from)
{
var copyto = new T1();
CopyEntity(copyto, f);
copyTo.Add(copyto);
}
return copyTo;
} private static object _sync = new object();
private static Dictionary<int, PropertyInfo[]> propDictionary = new Dictionary<int, PropertyInfo[]>(); /// <summary>
/// 获取指定类型的PropertyInfo缓存
/// </summary>
public static PropertyInfo[] PropCache<T>()
{
return PropCache(typeof(T));
} /// <summary>
/// 获取指定类型的PropertyInfo缓存
/// </summary>
public static PropertyInfo[] PropCache(object obj)
{
return PropCache(obj.GetType());
} /// <summary>
/// 获取指定类型的PropertyInfo缓存
/// </summary>
public static PropertyInfo[] PropCache(Type type)
{
int propCode = type.GetHashCode();
if (!propDictionary.ContainsKey(propCode))
{
lock (_sync)
{
if (!propDictionary.ContainsKey(propCode))
{
var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
List<PropertyInfo> tmplist = new List<PropertyInfo>();
foreach (var prop in props)
{
if (!prop.Name.StartsWith("__"))
{
tmplist.Add(prop);
}
}
propDictionary.Add(propCode, tmplist.ToArray());
}
}
} return propDictionary[propCode];
}
}
}

c# 实体处理工具类的更多相关文章

  1. HBaseConvetorUtil 实体转换工具

    HBaseConvetorUtil 实体转换工具类 public class HBaseConvetorUtil {        /**    * @Title: convetor    * @De ...

  2. Hibernate-validate工具类,手动调用校验返回结果

    引言:在常见的工程中,一般是在Controller中校验入参,校验入参的方式有多种,这里介绍的使用hibernate-validate来验证,其中分为手动和自动校验,自动校验可以联合spring,使用 ...

  3. mybatis的基本配置:实体类、配置文件、映射文件、工具类 、mapper接口

    搭建项目 一:lib(关于框架的jar包和数据库驱动的jar包) 1,第一步:先把mybatis的核心类库放进lib里

  4. POI读取excel工具类 返回实体bean集合(xls,xlsx通用)

    本文举个简单的实例 读取上图的 excel文件到 List<User>集合 首先 导入POi 相关 jar包 在pom.xml 加入 <!-- poi --> <depe ...

  5. Java工具类 通过ResultSet对象返回对应的实体List集合

    自从学了JDBC用多了像一下这种代码: List<xxx> list = new Array<xxx>(); if(rs.next()){ xxx x = new xxx(); ...

  6. 序列化工具类({对实体Bean进行序列化操作.},{将字节数组反序列化为实体Bean.})

    package com.dsj.gdbd.utils.serialize; import java.io.ByteArrayInputStream; import java.io.ByteArrayO ...

  7. xml文档的解析并通过工具类实现java实体类的映射:XML工具-XmlUtil

    若有疑问,可以联系我本人微信:Y1141100952 声明:本文章为原稿,转载必须说明 本文章地址,否则一旦发现,必追究法律责任 1:本文章显示通过 XML工具-XmlUtil工具实现解析soap报文 ...

  8. 浅拷贝工具类,快速将实体类属性值复制给VO

    /** * 浅拷贝的工具类 */ public class PropertiesUtil { /** * 两个类,属性名一样的元素,复制成员. */ public static void copy(O ...

  9. kettle系列-4.kettle定制化开发工具类

    要说的话这个工具类还是比较简单的,每个方法体都比较小,但用起来还是可以的,把开发中一些常用的步骤封装了下,不用去kettle源码中找相关操作的具体实现了. 算了废话不多了,直接上重点,代码如下: im ...

随机推荐

  1. CF1137F Matches Are Not a Child's Play(LCT思维题)

    题目 CF1137F 很有意思的题目 做法 直接考虑带修改的做法,上一次最大值为u,这次修改v,则最大值为v了 我们发现:\(u-v\)这条链会留到最后,序列里的其他元素相对位置不变,这条链会\(u\ ...

  2. 在Windows下安装运行Kafka

    一.安装JAVA JDK 1.下载安装包 http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151. ...

  3. [翻译]CSS模块-未来的编码方式

    前言 这是Glen Maddern发布于2015年8月19日的一篇文章,主要是之前翻译的文章<理解CSS模块方法>里提到这篇文章,现在算是顺藤摸瓜跟进来看看. 这里的翻译都是根据我自己的理 ...

  4. openwrt中的append-ubi定义在哪里

    include/image-commands.mk 定义如下: define Build/append-ubi sh $(TOPDIR)/scripts/ubinize-image.sh \ $(if ...

  5. NOIP2015 T4 推销员 贪心+堆优化

    前几天在学堆,这个数据结构貌似挺简单的,但是我看了很久啊QAQ... 今天算是搞懂了吧...于是想到了这道题...(当初悄悄咪咪看题解记得一点) 点我看题 放洛谷的题... 题意的话,大概就是有n个房 ...

  6. spark SQL学习(spark连接hive)

    spark 读取hive中的数据 scala> import org.apache.spark.sql.hive.HiveContext import org.apache.spark.sql. ...

  7. Vuex访问状态对象的方法

    除了<Vuex最基本样例>中的方法外,还有两种方法访问状态对象state: 只需要改app.vue文件 方法一:引入computed <template> <div id ...

  8. Struts2的select使用

    struts2的select标签中,常用的有以下几个属性:(1)struts2中的select 标签中,必须设置的属性只有一个,即是list.(2)select标签的list中必须有值,不然会报错.如 ...

  9. 用svg实现不规则形状

    像这种弧形,用纯html和css很难写,但是用svg就简单多了. 可以用作图工具画出一个弧形,然后导成svg格式.在页面中,下面的白块就是div+svg构成 mixin svgCard(...cont ...

  10. C++中输入输出十六进制八进制

    本文参考链接:https://www.cnblogs.com/hxsyl/archive/2012/09/18/2691693.html,经重新实验得此文 1.进制问题 默认情况下使用cin和cout ...