• C# 利用反射进行类型转换


     /// <summary>
            /// 父类转子类
            /// </summary>
            /// <typeparam name="TParent"></typeparam>
            /// <typeparam name="TChild"></typeparam>
            /// <param name="parent"></param>
            /// <returns></returns>
            public static TChild AutoCopy<TParent, TChild>(TParent parent) where TChild : TParent, new()
            {
                TChild child = new TChild();
                var ParentType = typeof(TParent);
                var Properties = ParentType.GetProperties();
                foreach (var Propertie in Properties)
                {
                    //循环遍历属性
                    if (Propertie.CanRead && Propertie.CanWrite)
                    {
                        //进行属性拷贝
                        Propertie.SetValue(child, Propertie.GetValue(parent, null), null);
                    }
                }
                return child;
            }
    
            /// <summary>
            /// 类型转换
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <typeparam name="R"></typeparam>
            /// <param name="obj"></param>
            /// <returns></returns>
            public static R ToResult<T, R>(T obj) where R : new()
            {
                R t = new R();
                var props = typeof(T).GetProperties().Where(a => a.CanRead && a.CanWrite);
                foreach (var item in props)
                {
                    item.SetValue(t, item.GetValue(obj, null), null);
                }
                return t;
            }
    
            /// <summary>
            /// 检查对象中的属性是有有null值
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="t"></param>
            /// <returns></returns>
            public static bool CheckObjHaveNullFiled<T>(T t)
            {
                if (t == null)
                {
                    return true;
                }
                else
                {
                    //属性列表
                    var proList = typeof(T).GetProperties();
    
                    return proList.Where(a => a.GetValue(t, null) == null || string.IsNullOrEmpty(a.GetValue(t, null).ToString().Trim())).Count() > 0;
                }
            }
    

      

  • 相关阅读:
    redis使用watch完成秒杀抢购功能:
    OAUTH协议
    常用mysql命令大全
    版本控制器 (Svn,Git)
    vue axios上传文件实例
    vue-resource 和 axios的区别
    js递归算法1+ 2+3.....100的和
    vue-cli title 里面怎动态显示文字
    Entity Framework With Mysql 之Code First
    关于a标签下的img元素在IE7下不能点击的问题
  • 原文地址:https://www.cnblogs.com/DONET-LC/p/10620385.html
Copyright © 2020-2023  润新知