简体   繁体   English

反射帮助-基于另一个对象在对象上设置属性

[英]Reflection Help - Set properties on object based on another object

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. 大多数(但不是全部)params属性存在于新对象中。

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
  }

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. 在“ Init”方法中,我需要遍历“ display”的属性,并将任何同名的“ DisabilityPaymentAddEntity”属性设置为preDisplay中的值。

Can anyone give me a clue what I need to do? 谁能给我一个线索,我需要做什么? I am sure I need to use PropertyInfo etc.. 我确定我需要使用PropertyInfo等。

Thanks, ~ck in San Diego 谢谢,〜ck在圣地亚哥

Something like this I think 我想是这样的

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);
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM