如何使用反射动态设置对象实例的属性值?

5

给定一个基本的类定义:

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也是简化的。
提前感谢您。

你的当前代码有什么问题? - cuongle
@CuongLe 它试图在类型为 System.Type 的实例上设置属于类型 Car 的属性值,这是行不通的。 - Rune FS
1个回答

9

您传递的第一个参数应该是持有要设置属性的实例。如果它是静态属性,则将第一个参数传递为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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接