C# assigns a value to an object through reflection

/// <summary>
   /// Reflection assignment
   /// </summary>
   public class ObjectReflection
   {
       public static PropertyInfo[] GetPropertyInfos(Type type)
       {
           return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
       }
       // / <summary>
       /// Entity attribute reflection
       /// </summary>
       /// <typeparam name="S">assignment object</typeparam>
       /// <typeparam name="T">assigned object<// 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);

Here, the value of the model attribute is assigned to the vmModel with the same attribute name.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325253639&siteId=291194637