zoukankan      html  css  js  c++  java
  • 反射复制对象

            #region 复制对象
            
    
            /// <summary>
            /// 将一个对象的属性给另一个对象的相同属性赋值
            /// </summary>
            /// <typeparam name="S">源对象类型</typeparam>
            /// <typeparam name="T">目标对象类型</typeparam>
            /// <param name="s">源对象</param>
            /// <param name="t">目标对</param>
            public static void AutoMapping<S, T>(S s, T t)
            {
                // get source PropertyInfos
                PropertyInfo[] pps = GetPropertyInfos(s.GetType());
                // get target type
                Type target = t.GetType();
    
                foreach (var pp in pps)
                {
                    PropertyInfo targetPP = target.GetProperty(pp.Name);
                    object value = pp.GetValue(s, null);
    
                    if (targetPP != null && value != null)
                    {
                        try
                        {
                            targetPP.SetValue(t, value, null);
                        }
                        catch (Exception)
                        {
    
                        }
    
                    }
                }
            }
    
    
            public static PropertyInfo[] GetPropertyInfos(Type type)
            {
                return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
            }
    
    
            #endregion
    

      

  • 相关阅读:
    装饰
    统一软件开发过程之2:用例文本书写
    统一软件开发过程之1:创建领域模型
    工厂方法
    volatile
    中介者
    建造者
    C#委托,事件与回调函数
    控件资源嵌入
    装饰
  • 原文地址:https://www.cnblogs.com/lhlong/p/9455141.html
Copyright © 2011-2022 走看看