如何设置通过反射对象属性 [英] How to set object property through Reflection
问题描述
我试图代码,将接受以下3个参数的方法:
I'm trying to code a method that will accept the following 3 arguments:
-
对象(用户定义类型这将发生变化)
an Object (user defined type which will vary)
代表该对象
一个属性名的字符串字符串值,将必须从一个字符串赋值之前的属性的数据类型转换。
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 figure 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.
任何帮助将不胜感激。
推荐答案
< A HREF =http://msdn.microsoft.com/en-us/library/xb5dd1f1.aspx相对=nofollow>的SetValue ,提供的 Convert.ChangeType 应该为你工作。使用您的代码:
SetValue with Convert.ChangeType should work for you. Using your code:
newValue = Convert.ChangeType(givenValue, prop.PropertyType);
prop.SetValue(target, newValue, null);
这篇关于如何设置通过反射对象属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!