简体   繁体   中英

Get property of object property by string in C#

How to access to property of property in object instance using string ? I would like automate changes i will made in form for example responding to object below:

class myObject{
   Vector3 position;
   public myObject(){
       this.position = new Vector3( 1d,2d,3d);
   }
};

Form have eg three numericUpDown called respectively position_X , position_Y , position_Z ; Instead having three callbacks for events as:

private void positionX_ValueChanged(object sender, EventArgs e)
  { 
    // this.model return myObject
    this.model().position.X = (double)  ((NumericUpDown)sender).Value;

  }

I would have one callback which can automatically set particular attribute in model from control name/tag

Below is javascript which describe purpose i want :)

position_Changed( sender ){
   var prop = sender.Tag.split('_'); ; // sender.Tag = 'position_X';      
   this.model[ prop[0] ] [ prop[1] ] = sender.Value;
}

You can use either reflection or expression trees to do that.

The simple reflection way (not very fast but versatile):

object model = this.model();
object position = model.GetType().GetProperty("position").GetValue(model);
position.GetType().GetProperty("X").SetValue(position, ((NumericUpDown)sender).Value);

Note: if Vector3 is a struct you may not get the expected results (but that has to do with structs and boxing, not with the code per se).

To complement the previous answer, which is essentially what you're looking for:

object model = this.model();
object position = model.GetType().GetProperty("position").GetGetMethod().Invoke(model, null);
var propName = (string) ((NumericUpDown)sender).Tag;
position.GetType().GetProperty(propName).GetSetMethod().Invoke(model, new [] {((NumericUpDown)sender).Value});

That is, you could just use the Tag property of Control to specify to which property of your Vector3 object the NumericUpDown instance is "bound" to.

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