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. [Android] 录音与播放录音实现

    http://blog.csdn.net/cxf7394373/article/details/8313980 android开发文档中有一个关于录音的类MediaRecord,一张图介绍了基本的流程 ...

  2. Django学习笔记之Web框架由浅入深和第一个Django实例

    Web框架本质 我们可以这样理解:所有的Web应用本质上就是一个socket服务端,而用户的浏览器就是一个socket客户端. 这样我们就可以自己实现Web框架了. 半成品自定义web框架 impor ...

  3. Python面试题之列表推导式

    题目要求: 生成如下列表 [[0,0,0,0,0,],[0,1,2,3,4,],[0,2,4,6,8,],[0,3,6,9,12,]] (考察列表生成式和基本逻辑推理) 方法1: list1 = [] ...

  4. 解决Linux 下server和client 通过TCP通讯:accept成功接收却报错的问题

    今天在写简单的TCP通讯例子的时候,遇到了一个问题:server 和client能够连接成功,并且client也能够正常发送,但server就是接收不到,在网上搜索一番后,终于解决了问题.在这里整理如 ...

  5. 20145310第一周JAVA实验报告

    20145310第一周JAVA实验报告 实验内容 1.使用JDK编译.运行简单的Java程序: 2.使用Eclipse 编辑.编译.运行.调试Java程序. 实验要求 使用JDK和IDE编译.运行简单 ...

  6. winlog

    下载 https://www.elastic.co/downloads/beats/winlogbeat PS C:\Users\Administrator> cd 'C:\Program Fi ...

  7. bellman-ford(可判负权回路+记录路径)

    #include<iostream> #include<cstdio> using namespace std; #define MAX 0x3f3f3f3f #define ...

  8. 将应用注册为Linux的服务

    主流的Linux大多使用init.d或systemd来注册服务.下面以centos6.6演示init.d注册服务:以centos7.1演示systemd注册服务. 1. 基于Linux的init.d部 ...

  9. PAT1070. Mooncake (25)

    #include #include #include <stdio.h> #include <math.h> using namespace std; struct SS{ d ...

  10. 网络软中断与NAPI函数分析

    网卡只有rx硬中断,外设通过中断控制器向CPU发出有数据包来临的通知, 而没有tx硬中断,因为发送数据包是cpu向外设发出的命令. ixgbe驱动的rx软中断和tx软中断在同一个CPU上处理. htt ...