简体   繁体   English

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

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

Given a basic class definition: 给出基本的类定义:

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

This code sample is simplified and not using dynamic type conversion, I just want a working sample to set that property on the instance. 此代码示例已简化,不使用动态类型转换,我只想要一个工作示例在实例上设置该属性。

Edit: PropertyName and PropertyValue in above code is also simplified. 编辑:上面代码中的PropertyName和PropertyValue也被简化了。

Thanks in advance 提前致谢

The first argument you pass should be the instance holding the property you wish to set. 您传递的第一个参数应该是包含您要设置的属性的实例。 If it's a static property pass null for the first argument. 如果它是静态属性,则为第一个参数传递null。 In your case change the code to: 在您的情况下,将代码更改为:

  public void setSpeed()
  {
       Type type = this.GetType(); 
       PropertyInfo property = type.GetProperty(PropertyName );
       property.SetValue(this, Convert.ToInt32(PropertyValue), null);
  }

for a naïve type conversion you could do 你可以做一个天真的类型转换

   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