首页 > Windows开发 > 详细

C# 通过反射为一个对象赋值

时间:2017-01-03 13:26:48      阅读:386      评论:0      收藏:0      [点我收藏+]

/// <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。

C# 通过反射为一个对象赋值

原文:http://www.cnblogs.com/oreobyzf/p/6244366.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!