繁体   English   中英

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

[英]How to dynamically set the value of a property of object instance using reflection?

给出基本的类定义:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM