C# 使用用户输入更改属性
我有一个简单的类,它有两个属性:C# 使用用户输入更改属性,c#,C#,我有一个简单的类,它有两个属性: 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"); 在同一个类中,我有一个圆形对象,我只想根据他的选择将属性的值
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;
这只是一个小例子,我想知道主要的想法,所以两个小的“如果”不会有帮助…谢谢大家! 我想你应该使用反射
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);
这应该会给你一个主意。试试这样的方法:
circle.GetType().GetProperty(selectProperty).SetValue(circle,5)
你想达到什么目的?@Fabjan这不起作用。。。知道为什么吗?@AmitKumarGhosh我正在尝试更改用户选择的特定属性。与编辑页类似。@user7399016一个可能的原因是属性的访问修饰符受保护,您可以将其更改为public
或在GetProperty
方法中使用Bindingflags重载。PropertyInfo是什么?反射命名空间的一个类,它提供了动态访问类属性的功能(在您的情况下,您是通过名称访问属性)。看一看.NET反射教程。基本上,您可以在运行时访问编译过的对象,这给了您很大的可能性。