首页 > Windows开发 > 详细

C# 利用反射给不同类型对象同名属性赋值

时间:2016-09-20 13:46:27      阅读:358      评论:0      收藏:0      [点我收藏+]
    public class ObjectReflection
    {
        public static PropertyInfo[] GetPropertyInfos(Type type)
        {
            return type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
        }

        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)
                {
                    targetPP.SetValue(t, value, null);
                }
            }
        }

调用方式

//Class1 objfrom,Class2 objto;


ObjectReflection.AutoMapping<Class1, Class2>(objfrom, objto);
//将 objfrom 的属性复制给objto的同名属性。

 

C# 利用反射给不同类型对象同名属性赋值

原文:http://www.cnblogs.com/sxypeace/p/5888345.html

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