通过反射向对象取值和赋值

2021-04-23
通过反射向对象取值和赋值
 public void Test6()
        {
            List<RepaymentRecord> repaymentList = new List<RepaymentRecord>();

            StringBuilder msg = new StringBuilder();
            RepaymentRecord entity = new RepaymentRecord();
            entity.Month1 = "100";
            entity.Month18 = "900";
            entity.Month24 = "322";
            foreach (PropertyInfo p in entity.GetType().GetProperties())
            {
                msg.AppendFormat("{0},{1}", p.Name, p.GetValue(entity));
            }
            var result = msg;
            Assert.IsNotNull(result);
        }

 

 

/// <summary>
   /// 反射赋值
   /// </summary>
   public class ObjectReflection
   {
       public static PropertyInfo[] GetPropertyInfos(Type type)
       {
           return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
       }
       /// <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)
       {
           PropertyInfo[] pps = GetPropertyInfos(s.GetType());
           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)
               {
                   targetPP.SetValue(t, value, null);
               }
           }
       }
   }
用法  ObjectReflection.AutoMapping(model, vmModel);

这里将model属性的值赋值给了具体相同属性名称的vmModel。