本文翻译自:Setting a property by reflection with a string value
I'd like to set a property of an object through Reflection, with a value of type string
. 我想通过Reflection设置对象的属性,其值为string
类型。 So, for instance, suppose I have a Ship
class, with a property of Latitude
, which is a double
. 因此,例如,假设我有一个Ship
类,其属性为Latitude
,这是一个double
。
Here's what I'd like to do: 这是我想做的事情:
Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, value, null);
As is, this throws an ArgumentException
: 原样,这会抛出ArgumentException
:
Object of type 'System.String' cannot be converted to type 'System.Double'. “System.String”类型的对象无法转换为“System.Double”类型。
How can I convert value to the proper type, based on propertyInfo
? 如何根据propertyInfo
将值转换为正确的类型?
#1楼
参考:https://stackoom.com/question/4ZKV/通过反射使用字符串值设置属性
#2楼
As several others have said, you want to use Convert.ChangeType
: 正如其他几个人所说,你想使用Convert.ChangeType
:
propertyInfo.SetValue(ship,
Convert.ChangeType(value, propertyInfo.PropertyType),
null);
In fact, I recommend you look at the entire Convert
Class . 实际上,我建议你看看整个Convert
类 。
This class, and many other useful classes are part of the System
Namespace . 此类和许多其他有用的类是System
Namespace的一部分。 I find it useful to scan that namespace every year or so to see what features I've missed. 我发现每年扫描一个命名空间很有用,看看我错过了哪些功能。 Give it a try! 试试看!
#3楼
You can use Convert.ChangeType()
- It allows you to use runtime information on any IConvertible
type to change representation formats. 您可以使用Convert.ChangeType()
- 它允许您使用任何IConvertible
类型的运行时信息来更改表示格式。 Not all conversions are possible, though, and you may need to write special case logic if you want to support conversions from types that are not IConvertible
. 但是,并非所有转换都是可能的,如果您希望支持非IConvertible
类型的转换,则可能需要编写特殊情况逻辑。
The corresponding code (without exception handling or special case logic) would be: 相应的代码(无异常处理或特殊情况逻辑)将是:
Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);
#4楼
Or you could try: 或者你可以尝试:
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);
//But this will cause problems if your string value IsNullOrEmplty...
#5楼
You're probably looking for the Convert.ChangeType
method. 您可能正在寻找Convert.ChangeType
方法。 For example: 例如:
Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);
#6楼
Using Convert.ChangeType
and getting the type to convert from the PropertyInfo.PropertyType
. 使用Convert.ChangeType
并从PropertyInfo.PropertyType
获取要转换的类型。
propertyInfo.SetValue( ship,
Convert.ChangeType( value, propertyInfo.PropertyType ),
null );