zoukankan      html  css  js  c++  java
  • 父子类型转换

     /// <summary>
            /// 自动映射父类数据到子类
            /// </summary>
            /// <typeparam name="TParent"></typeparam>
            /// <typeparam name="TChild"></typeparam>
            /// <param name="parent"></param>
            /// <returns></returns>
            public static TChild AutoMapper<TParent, TChild>(TParent parent) where TChild : TParent, new()
            {
                TChild child = new TChild();
                Type ParentType = typeof(TParent);
                var Properties = ParentType.GetRuntimeProperties();
                foreach (PropertyInfo Propertie in Properties)
                {
                    //循环遍历属性
                    if (Propertie.CanRead && Propertie.CanWrite)
                    {
                        //进行属性拷贝
                        Propertie.SetValue(child, Propertie.GetValue(parent, null), null);
                    }
                }
                return child;
            }
    
            /// <summary>
            /// 没有继承约束,但是有共同属性,剪除部分属性后可视为目标属性
            /// </summary>
            /// <typeparam name="TParent"></typeparam>
            /// <param name="me"></param>
            /// <returns></returns>
            public static TParent TryToParent<TParent>(this object me) where TParent : new()
            {
                
                TParent res = new TParent();
                Type pt = typeof(TParent);
                try
                {
                    var ps = pt.GetRuntimeProperties().ToList();
                    foreach (PropertyInfo p in ps)
                    {
                        //循环遍历属性
                        if (p.CanRead && p.CanWrite)
                        {
                            //进行属性拷贝
                            p.SetValue(res, p.GetValue(me, null), null);
                        }
                    }
                    return res;
                }
                catch (Exception e)
                {
                    throw new Exception($"实体转换失败,请检查属性是否一致{me?.GetType()?.Name}:{pt.Name}");
                }
            }
  • 相关阅读:
    innerHTML与innerText区别
    HTML5中的数据集dataset和自定义属性data-*
    HTTP协议
    Javascript 中的 && 和 || 使用小结
    JavaScript 实现回文解码
    sublime中用less实现css预编译
    jQuery事件绑定的四种方法
    前端学习过程中需要看的书籍
    Echarts学习宝典
    Vue插槽
  • 原文地址:https://www.cnblogs.com/zhuwansu/p/11822105.html
Copyright © 2011-2022 走看看