0

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;
}
1
  • If you are doing lots of this, you might want to look at FastMember Commented Sep 7, 2012 at 22:20

2 Answers 2

3

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.