[深入学习C#]利用反射给对象赋值

转载自诗人江湖老,原文地址
 C#中利用反射能够获取对象的属性信息,也可以利用反射给对象赋值。
我们如果想利用凡是给一个对象属性赋值可以通过PropertyInfo.SetValue()方式进行赋值,但要注意值的类型要与属性保持一致。

  假设我们有如下一个结构:

struct Person
{
        public string code{get; set;}
        public string name{get; set;}
}

  下面一段代码,展示了如何利用反射来给对象赋值:
  

Person p =new Person(){code="123456", name="Jay"};
Person item=new Person();
PropertyInfo[] props=p.GetType().GetProperties();
props.ToList().ForEach(
    pi=>
    {
          if (!pi.PropertyType.IsGenericType)
                    {
                        if (pi.GetValue(p) != null)
                        {
                            pi.SetValue(item, Convert.ChangeType(pi.GetValue(p), pi.PropertyType));
                        }
                    }
                    else
                    {
                        Type genericTypeDefinition = pi.PropertyType.GetGenericTypeDefinition();
                        if (genericTypeDefinition == typeof(Nullable<>))
                        {
                            if (pi.GetValue(p) != null)
                            {
                                pi.SetValue(item, Convert.ChangeType(pi.GetValue(p), Nullable.GetUnderlyingType(pi.PropertyType)));
                            }
                        }
                    });

   pi.SetValue(item, Convert.ChangeType(pi.GetValue(p), pi.PropertyType))
   pi.SetValue(item, Convert.ChangeType(pi.GetValue(p), Nullable.GetUnderlyingType(pi.PropertyType)))
   这两行代码,分别是给非泛型属性赋值和给泛型属性赋值。

猜你喜欢

转载自blog.csdn.net/xuchen_wang/article/details/86524046