如何通过Reflection设置对象属性

时间:2011-03-20 18:53:19

标签: c# reflection

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

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

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

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

  4. 方法签名如下所示:

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

    问题在于我无法弄清楚如何设置属性值。此外,该值以字符串形式出现,因此我必须在属性的数据类型之前检查该值的数据类型,然后才能对其进行强制转换。分配

    非常感谢任何帮助。

3 个答案:

答案 0 :(得分:4)

带有SetValue

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

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

答案 1 :(得分:1)

您正在寻找SetValue。

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

e.g。 Setting a property by reflection with a string value

答案 2 :(得分:1)

prop.SetValue(target,new TypeConverter().ConvertFromString(propertyValue));
相关问题