开发者

How to set object property through Reflection [duplicate]

This question already has answers here: Set object property using reflection (10 answers) Closed 9 years ago.

I'm trying to code a method that will accept the following 3 arguments:

  1. an Object (user defined type which will vary)

  2. a string representing a property name for that object

  3. a string value, which will have to be converted from a string to the property's data type prior to assignment.

The method signature will look like this:

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

I've found how to retrieve a property value with Reflection with the following code:

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

The problem is that I can't f开发者_如何学运维igure out how to set the property value. Also, the value is coming in as a string, so I have to check the data type of the value against the property's datatype before it can be cast & assigned.

Any help would be greatly appreciated.


SetValue with Convert.ChangeType should work for you. Using your code:

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


SetValue is what you are looking for.

There are plenty of questions on here with sample code (take a look at the Related Question list on the right of this page)

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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜