简体   繁体   中英

Using user input to change a property

I have a simple class with 2 properties:

    class Circle {
protected int x = 0 {get; set;}
protected int y = 0 {get; set;} 
}

I have another class where the user can write which property he wants to change.

string selectProperty = Input.ReadString("Write which property to you want to change");  

In the same class I have a circle object, and I just want to change the value of a property according to his selection, to 5.

circle.selectProperty = 5;

This is just small example, I want to know the main idea, so 2 small "if"s won't help...
Thank you!

I think you want to use reflection.

Circle circle = new Circle();
string selectProperty = Input.ReadString("Write which property to you want to change");
string selectedValue = Input.ReadString("Write which value should be written");
PropertyInfo propertyInfo = circle.GetType().GetProperty(selectedProperty);
propertyInfo.SetValue(circle, Convert.ChangeType(selectedValue, propertyInfo.PropertyType), null);

That should give you an idea.

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