简体   繁体   中英

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.

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.

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

Thanks, ~ck in San Diego

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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