Reflection Help - Set properties on object based o

2019-03-01 18:00发布

问题:

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

回答1:

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