【问题标题】:How to set object property through Reflection [duplicate]如何通过反射设置对象属性[重复]
【发布时间】:2011-07-19 05:51:17
【问题描述】:

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

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

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

问题是我不知道如何设置属性值。此外,该值是以字符串形式出现的,因此我必须根据属性的数据类型检查值的数据类型,然后才能对其进行强制转换和分配。

任何帮助将不胜感激。

【问题讨论】:

标签: c# reflection


【解决方案1】:
prop.SetValue(target,new TypeConverter().ConvertFromString(propertyValue));

【讨论】:

  • 如果没有第三个参数(null),这对我来说无法编译,然后出现“TypeConverter 无法从 System.String 转换”错误。我不知道。无论哪种情况,我都需要尝试转换为特定的数据类型(prop.PropertyType)。
【解决方案2】:

SetValue 就是你要找的。​​p>

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

例如Setting a property by reflection with a string value

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 奥斯汀,你是男人!这很好用。我使用 var 作为 newValue 的类型声明( newValue = Convert.ChangeType(givenValue, prop.PropertyType);)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-02-28
    • 1970-01-01
    • 2010-10-26
    • 2010-10-11
    • 2018-02-07
    • 1970-01-01
    相关资源
    最近更新 更多