如何通过Reflection 设置对象属性

我正在尝试编写一个接受以下3个参数的方法:

  1. 一个Object(用户定义的类型会有所不同)

  2. 表示该对象的属性名称的字符串

  3. 字符串值,在分配之前必须从字符串转换为属性的数据类型。

方法签名如下所示:

public void UpdateProperty(Object obj, string propertyName, string value) 

我已经找到了如何使用以下代码检索属性值:

 PropertyInfo[] properties = target.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in properties) { if (string.Compare(prop.Name, propertyName, true) == 0) { return prop.GetValue(target, null).ToString(); } } 

问题是我无法弄清楚如何设置属性值。 此外,该值以字符串forms出现,因此我必须根据属性的数据类型检查值的数据类型,然后才能进行转换和分配。

任何帮助将不胜感激。

使用Convert.ChangeType的 SetValue应该适合你。 使用你的代码:

 newValue = Convert.ChangeType(givenValue, prop.PropertyType); prop.SetValue(target, newValue, null); 

SetValue正是您要找的。

这里有很多关于示例代码的问题(请参阅本页右侧的相关问题列表)

例如, 通过reflection用字符串值设置属性

 prop.SetValue(target,new TypeConverter().ConvertFromString(propertyValue));