zoukankan      html  css  js  c++  java
  • 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;
                }
            }
    

      

  • 相关阅读:
    ESFramework Demo -- 动态组及群聊Demo(附源码)
    反射整理学习
    JavaScript 每周导读
    SQLSERVER 中的 with锁级别
    代码细节重构:请对我的代码指手划脚
    SQLServer查询死锁语句
    模块加载系统 v16
    数据结构之排序算法C#实现
    浅谈操作系统对内存的管理
    如何编写可维护的面向对象JavaScript代码
  • 原文地址:https://www.cnblogs.com/DONET-LC/p/10620385.html
Copyright © 2011-2022 走看看