C#一样格式类型互转

来源:互联网 发布:骑士数据 编辑:程序博客网 时间:2024/05/21 11:17
 public class TypeConverter
    {
        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;
        }
        public static Toutput Convert<Tinput, Toutput>(Tinput sourceObject) where Toutput : class
        {


            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;
            }






            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);
            }
        }
    }
0 0
原创粉丝点击