2017-01-10 56 views
2

我有一个简单的类有2个属性:利用用户输入更改属性

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

我有另一个类,用户可以写他想要更改的属性。

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

在同一个类我有一个圆形对象,我只是想改变根据他的选择一个物业的价值,5

circle.selectProperty = 5; 

这只是小例子,我想知道主要想法,所以2小“如果”不会帮助...
谢谢!

+1

尝试这样:'circle.GetType()。GetProperty(selectProperty).SetValue(circle,5)' – Fabjan

+0

你想达到什么目的? –

+0

@Fabjan这不工作......任何想法为什么? – user7399016

回答

2

我想你想使用反射。

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

这应该给你一个想法。

+0

什么是PropertyInfo的东西? – user7399016

+0

反射命名空间的一个类,它提供了动态访问类的属性的功能(在您的情况下,您通过其名称访问属性)。看看.NET反射教程。基本上你可以在运行时访问编译对象,这给你很大的可能性。 –