其他分享
首页 > 其他分享> > 父子类实体类属性值转换(有值子类转无值实体类)

父子类实体类属性值转换(有值子类转无值实体类)

作者:互联网

 /// <summary>
        /// 父子类属性赋值
        /// </summary>
        /// <typeparam name="D">空实体类</typeparam>
        /// <typeparam name="S">有值实体类</typeparam>
        /// <param name="s">有值实体类</param>
        /// <returns>赋值后的空实体类</returns>
private static D Mapper<D, S>(S s)
        {
            D d = Activator.CreateInstance<D>();
            try
            {
                Type type = s.GetType();
                Type typeFromHandle = typeof(D);
                PropertyInfo[] properties = type.GetProperties();
                for (int i = 0; i < properties.Length; i++)
                {
                    PropertyInfo propertyInfo = properties[i];
                    PropertyInfo[] properties2 = typeFromHandle.GetProperties();
                    for (int j = 0; j < properties2.Length; j++)
                    {
                        PropertyInfo propertyInfo2 = properties2[j];
                        if (propertyInfo2.Name == propertyInfo.Name)
                        {
                            propertyInfo2.SetValue(d, propertyInfo.GetValue(s, null), null);
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
            return d;
        }

 

标签:实体类,有值,子类,PropertyInfo,propertyInfo2,propertyInfo,properties
来源: https://www.cnblogs.com/yuanshuo/p/15036173.html