反射帮助-基于另一个对象在对象上设置属性 [英] Reflection Help - Set properties on object based on another object

查看:65
本文介绍了反射帮助-基于另一个对象在对象上设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以使用一些帮助.我正在将一个对象传递给另一个对象的构造函数.我需要遍历参数的属性并基于它设置新的对象属性.大多数(但不是全部)params属性存在于新对象中.

I could use a bit of relection help. I am passing an object into the constructor of another object. I need to loop through the parameter's properties and set the new objects properties based on it. Most, but not all, of the params properties exist in the new object.

到目前为止,我已经有了基本骨架.

I have this so far, the basic skeleton.

  public DisabilityPaymentAddEntity(DisabilityPaymentPreDisplayEntity preDisplay)
  {
      Init(preDisplay);
  }

  private void Init(DisabilityPaymentPreDisplayEntity display)
  {
       //need some type of loop using reflection here
  }

在'Init'方法中,我需要遍历'display'的属性,并将任何同名的'DisabilityPaymentAddEntity'属性设置为preDisplay中的值.

In the 'Init' method, I need to loop through 'display's properties and set any of 'DisabilityPaymentAddEntity' properties of the same name to values in the preDisplay.

谁能给我一个线索,我需要做什么?我确定我需要使用PropertyInfo等.

Can anyone give me a clue what I need to do? I am sure I need to use PropertyInfo etc..

谢谢, 圣地亚哥〜ck

Thanks, ~ck in San Diego

推荐答案

我认为这样的事情

Type target = typeof(DisabilityPaymentAddEntity);
foreach(PropertyInfo pi in display.GetType().GetProperties())
{
     PropertyInfo targetProp = target.GetProperty(pi.Name);
     if(targetProp!=null)
     {
        targetProp.SetValue(this, pi.GetValue(display, null), null);
     }
}

这篇关于反射帮助-基于另一个对象在对象上设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆