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. 一.复习GCC编译器的用法

    1.复习GCC编译器的用法 欲善其工,那么要先利其器.在这个C语言巩固与提高的阶段中,如果想要更好的达成预期目标,首先就要熟练掌握GCC编译器的用法.以下是GCC相关知识: GCC使用语法 gcc 选 ...

  2. logstash编写2以及结合kibana使用

    有时候根据日志的内容,可能一行不能全部显示,会延续在下一行,为了将上下内容关联在一起,于是codec插件中的multiline插件 就派上用场了,源日志内容: [2017-09-20T16:04:34 ...

  3. 20145307第四次JAVA学习实验报告

    20145307实验四 Android开发基础 实验内容 基于Android Studio开发简单的 Android应用并部署测试; 了解Android组件.布局管理器的使用: 掌握Android中事 ...

  4. LeetCode——Single Element in a Sorted Array

    Question Given a sorted array consisting of only integers where every element appears twice except f ...

  5. 转载 URL短地址压缩算法

    文章转载http://www.nowamagic.net/webdesign/webdesign_ShortUrlInTwitter.php /// <summary> /// 生成sal ...

  6. pyspider—爬取下载图片

    以第一ppt网站为例:http://www.1ppt.com/ from pyspider.libs.base_handler import * import urllib2,HTMLParser,r ...

  7. Ubuntu+apache安装redmin

    公司要迁移redmin,本来以为是一个很简单的项目,想不到整整搞了一天加一个晚上. 首先是对ruby的安装不熟悉,现在明白了ruby的安装顺序是先安装rvm版本管理,然后用rvm安装ruby,安装好后 ...

  8. 做文件上传下载时报这个错com.alibaba.fastjson.JSONException: illegal identifier : \

    ::-exec-] DEBUG c.i.e.m.I.insertDataEmebeding - <== Updates: ::-exec-] ERROR c.i.e.c.CaseArchiveC ...

  9. input实现文件上传

    input实现文件上传 input + ajax 实现文件上传,包括文件大小及类型的判断 一.html <input type="file" id="file&qu ...

  10. jquery.chosen.js下拉选择框美化插件项目实例

    由于之前使用的bootstrap-select插件是建立在bootstrap基础上的,实际使用到项目中的时候,与我们使用的ace-admin(基于bootstrap)存在样式冲突,导致下拉框的样式发生 ...