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

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

 

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

上一篇:这年头,做数据分析师还需要沟通小技巧!?


下一篇:如何查找MagSafe电池组的序列号?