同一种类型的两个对象赋值,用反射。再也不用点属性了。。。。(适用于ef)

/// <summary>
        /// 给对象赋值的方法(不赋地址)(同一个类型),含过滤
        /// </summary>
        /// <typeparam name="T"><peparam>
        /// <param name="left">=号左边</param>
        /// <param name="right">=号右边</param>
        /// <param name="id">过滤条件</param>
        public static void Assignment<T>(T left, T right, string id=null)
        {
            Type type = left.GetType();
            List<PropertyInfo> pList = type.GetProperties().ToList();
            for (int i = 0; i < pList.Count; i++)
            {
                //根据属性名获得指定的属性对象
                PropertyInfo gc = type.GetProperty(pList[i].Name);
                //设置属性的值
                if (id != null) 
                {
                    if (pList[i].Name != id) 
                    {
                        gc.SetValue(left, pList[i].GetValue(right, null), null);
                    }
                }
                else 
                {
                    gc.SetValue(left, pList[i].GetValue(right, null), null);
                }
               
            }
        }
View Code

 

posted @ 2015-08-21 15:24  小小高  阅读(901)  评论(0编辑  收藏  举报