c# 实体处理工具类
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# 实体处理工具类的更多相关文章
- HBaseConvetorUtil 实体转换工具
HBaseConvetorUtil 实体转换工具类 public class HBaseConvetorUtil { /** * @Title: convetor * @De ...
- Hibernate-validate工具类,手动调用校验返回结果
引言:在常见的工程中,一般是在Controller中校验入参,校验入参的方式有多种,这里介绍的使用hibernate-validate来验证,其中分为手动和自动校验,自动校验可以联合spring,使用 ...
- mybatis的基本配置:实体类、配置文件、映射文件、工具类 、mapper接口
搭建项目 一:lib(关于框架的jar包和数据库驱动的jar包) 1,第一步:先把mybatis的核心类库放进lib里
- POI读取excel工具类 返回实体bean集合(xls,xlsx通用)
本文举个简单的实例 读取上图的 excel文件到 List<User>集合 首先 导入POi 相关 jar包 在pom.xml 加入 <!-- poi --> <depe ...
- Java工具类 通过ResultSet对象返回对应的实体List集合
自从学了JDBC用多了像一下这种代码: List<xxx> list = new Array<xxx>(); if(rs.next()){ xxx x = new xxx(); ...
- 序列化工具类({对实体Bean进行序列化操作.},{将字节数组反序列化为实体Bean.})
package com.dsj.gdbd.utils.serialize; import java.io.ByteArrayInputStream; import java.io.ByteArrayO ...
- xml文档的解析并通过工具类实现java实体类的映射:XML工具-XmlUtil
若有疑问,可以联系我本人微信:Y1141100952 声明:本文章为原稿,转载必须说明 本文章地址,否则一旦发现,必追究法律责任 1:本文章显示通过 XML工具-XmlUtil工具实现解析soap报文 ...
- 浅拷贝工具类,快速将实体类属性值复制给VO
/** * 浅拷贝的工具类 */ public class PropertiesUtil { /** * 两个类,属性名一样的元素,复制成员. */ public static void copy(O ...
- kettle系列-4.kettle定制化开发工具类
要说的话这个工具类还是比较简单的,每个方法体都比较小,但用起来还是可以的,把开发中一些常用的步骤封装了下,不用去kettle源码中找相关操作的具体实现了. 算了废话不多了,直接上重点,代码如下: im ...
随机推荐
- 一幅图秒懂LoadAverage(转载)
转自:http://www.habadog.com/2015/02/27/what-is-load-average/ 一幅图秒懂LoadAverage(负载) 一.什么是Load Average? ...
- RabbitMQ学习之(五)_一个基于PHP的RabbitMQ操作类
//amqp.php类文件 <?php class Amqp { public $e_name; public $q_name; public $k_route; public $channel ...
- 20145103JAVA第二次实验报告
实验二 Java面向对象程序设计 实验内容 1.初步掌握单元测试和TDD 2.理解并掌握面向对象三要素:封装.继承.多态 3.初步掌握UML建模 4.熟悉S.O.L.I.D原则 5.了解设计模式 实验 ...
- word里怎么删除某一列
光标定位在第二列第一个字的前面,然后按住Alt键,拖动鼠标,选中第二列字,松开Alt键,点击Delete键即可
- 5.scala中的对象
排版乱?请移步原文获得更好的阅读体验 1.单例对象 scala中没有静态类或者静态方法,都是通过object实现的,它表示某个类的单例对象.如object People是class People的单例 ...
- "ImportError: cannot import name OVSLegacyKernelSwitch"
My VirtualMachine OS is Ubuntu14.04, Linux. Recently I want to install the mininet in my OS, and I u ...
- servlet初始化参数
使用<context-param>标签初始化的参数是被应用程序中所有的servlet所共享.但是有时候我们需要为某一个特定的servlet配置参数,这个时候我们就需要使用servlet初始 ...
- openstack dpdk
# ovs-vsctl showeef7cd95-0677-486c-b119-5d6ac8531c56 Manager "ptcp:6640:127.0.0.1" is_conn ...
- 【转发】Linux中设置服务自启动的三种方式
有时候我们需要Linux系统在开机的时候自动加载某些脚本或系统服务 主要用三种方式进行这一操作: ln -s 在/etc/rc.d/rc*.d目录中建立/e ...
- centos 7网速监控脚本
#!/bin/bashif [ $# -ne 1 ];thendev="eth0"elsedev=$1fi while :doRX1=`/sbin/ifconfig $dev |a ...