C# 如何使用反射动态设置对象实例属性的值?
给出基本类定义:C# 如何使用反射动态设置对象实例属性的值?,c#,C#,给出基本类定义: using System.Reflection; public class Car() { public int speed {get;set;} public void setSpeed() { Type type = this.GetType(); PropertyInfo property = type.GetProperty(PropertyName ); property.SetValue(type, Con
using System.Reflection;
public class Car()
{
public int speed {get;set;}
public void setSpeed()
{
Type type = this.GetType();
PropertyInfo property = type.GetProperty(PropertyName );
property.SetValue(type, Convert.ToInt32(PropertyValue), null);
}
}
这个代码示例是简化的,没有使用动态类型转换,我只需要一个工作示例来设置实例的属性
编辑:上面代码中的PropertyName和PropertyValue也被简化了
提前感谢您传递的第一个参数应该是包含要设置的属性的实例。如果是静态属性,则为第一个参数传递null。在您的情况下,将代码更改为:
public void setSpeed()
{
Type type = this.GetType();
PropertyInfo property = type.GetProperty(PropertyName );
property.SetValue(this, Convert.ToInt32(PropertyValue), null);
}
对于幼稚的类型转换,您可以
var value = Convert.ChangeType(PropertyValue,property.PropertyType);
property.SetValue(this, value, null);
当前代码有什么问题?@CuongLe它试图在类型
System.type的实例上设置属于类型Car
的属性值,但该类型无效