- using System;
- using System.Reflection;
- using System.Collections;
- using System.Collections.Generic;
- namespace Common.Helpers
- {
- /// <summary>
- /// 类型转换器(利用反射)
- /// </summary>
- public static class TypeConverter
- {
- #region 相同结构的类的转换
- /// <summary>
- /// 类型转换(相同结构的类的转换,如果当前类中的属性在源对象属性中不存在,则忽略该属性)
- /// </summary>
- /// <param name="arrSourceObjects">源对象数组</param>
- /// <param name="toType">目标类型</param>
- /// <returns>目标对象</returns>
- public static List<Toutput> ConvertAll<Tinput, Toutput>(List<Tinput> arrSourceObjects) where Toutput : class
- {
- if (arrSourceObjects != null)
- {
- List<Toutput> list = new List<Toutput>();
- foreach (Tinput obj in arrSourceObjects)
- {
- list.Add(Convert<Tinput, Toutput>(obj));
- }
- return list;
- }
- return null;
- }
- /// <summary>
- /// 类型转换(相同结构的类的转换,如果当前类中的属性在源对象属性中不存在,则忽略该属性)
- /// </summary>
- /// <param name="sourceObject">源对象</param>
- /// <param name="toType">目标类型</param>
- /// <returns>目标对象</returns>
- public static Toutput Convert<Tinput, Toutput>(Tinput sourceObject) where Toutput : class
- {
- #region 基础处理
- if (sourceObject == null)
- {
- return null;
- }
- Type sourceType = typeof(Tinput);
- Type toType = typeof(Toutput);
- //若为子类,直接返回源对象
- Toutput returnObject = sourceObject as Toutput;
- if (returnObject != null)
- {
- return sourceObject as Toutput;
- }
- #endregion
- try
- {
- returnObject = Activator.CreateInstance(toType) as Toutput; //转换后的对象
- PropertyInfo[] targetObjProperties = toType.GetProperties(); //目标对象的属性信息
- foreach (PropertyInfo objProperty in targetObjProperties)
- {
- //获取源对象对应属性的值,赋予新对象(当两个属性的类型一致或可转化时赋值)
- PropertyInfo sourcePropertyInfo = sourceType.GetProperty(objProperty.Name);
- if (sourcePropertyInfo != null && objProperty.PropertyType.IsAssignableFrom(sourcePropertyInfo.PropertyType))
- {
- object objSourceValue = sourcePropertyInfo.GetValue(sourceObject, null);
- objProperty.SetValue(returnObject, objSourceValue, null);
- }
- }
- return returnObject;
- }
- catch (Exception ex)
- {
- string strMsg = string.Format("源类型{0}转换成目标类型{1}时失败,失败原因:{2}", sourceType, toType, ex.Message);
- throw new ApplicationException(strMsg, ex);
- }
- }
- #endregion
- }
- }
利用反射强制转换结构相同的类(类之间无需有继承关系)
最新推荐文章于 2023-04-28 16:58:40 发布