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. 用C#连接SFTP服务器并进行上传下载文件

    1.使用软件连接可采用WinSCP进行: 文件协议选择SFTP,端口号默认22 2.使用C#代码操作 参考:http://www.cnblogs.com/binw/p/4065642.html 主要引 ...

  2. JavaScript&jQuery获取url参数方法

    JavaScript&jQuery获取url参数方法 function getUrlParam(name){ var reg = new RegExp("(^|&)" ...

  3. Linux ASLR的实现

    ASLR大家都会听说过,但是Linux平台下应用程序的ASLR的情况是怎么样的呢?我在这里将ASLR分为几个小的部分来阐述,包括了栈的随机化,堆的随机化,mmap的随机化,以及pie程序运行时的主模块 ...

  4. win10下搭建jz2440v3(arm s3c2440)开发及gdb调试环境【转】

    本文转载自:https://blog.csdn.net/newjay03/article/details/72835758 本来打算完全在Ubuntu下开发的,但是水平有限,没有在Ubuntu下找到合 ...

  5. LeetCode——Find All Duplicates in an Array

    Question Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice an ...

  6. c#实现任务栏添加控制按钮

    Windows7Taskbar的使用 你需要引入3个文件VistaBridgeLibrary.dll.Windows7.DesktopIntegration.dll.Windows7.DesktopI ...

  7. 解题报告:codeforce 7C Line

    codeforce 7C C. Line time limit per test1 second memory limit per test256 megabytes A line on the pl ...

  8. POJ2159 ancient cipher - 思维题

    2017-08-31 20:11:39 writer:pprp 一开始说好这个是个水题,就按照水题的想法来看,唉~ 最后还是懵逼了,感觉太复杂了,一开始想要排序两串字符,然后移动之类的,但是看了看 好 ...

  9. Dropping water balloons (入门dp)

    2017-08-12 18:36:24 writer:pprp 最近刚刚接触动态规划,感觉状态的查找和转移自己很难想到,都是面向题解编程,但是一开始都是这样了,只有相信我可以独立自己解决动态规划这类问 ...

  10. 你不知道的东西! c# == 等于运算符 和 Object.Equals()

    最近在看 高级点的程序员必看的     CLR via C#    书中说解释了 Object.Equals()  方法的实现, 其中具体的实现用的是 == 运算符 ! 以前就对 == 运算符 的具体 ...