我想通过反射设置一个对象的属性,值类型为字符串。 例如,假设我有一个Ship类,它的纬度属性是double。

这是我想做的:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, value, null);

这将抛出一个ArgumentException:

类型为System的对象。字符串'不能转换为'System.Double'类型。

如何将值转换为适当的类型,基于propertyInfo?


当前回答

你可以使用Convert.ChangeType() -它允许你在任何IConvertible类型上使用运行时信息来更改表示格式。但是,并不是所有的转换都是可能的,如果您希望支持从非IConvertible类型转换,则可能需要编写特殊情况的逻辑。

相应的代码(没有异常处理或特殊情况逻辑)将是:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);

其他回答

使用下面的代码可以解决你的问题:

item.SetProperty(prop.Name, Convert.ChangeType(item.GetProperty(prop.Name).ToString().Trim(), prop.PropertyType));

你可能在找皈依者。ChangeType功能。例如:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);

我注意到很多人都推荐Convert。ChangeType -这在某些情况下确实有效,但是一旦你开始涉及可空类型,你就会开始收到InvalidCastExceptions:

http://weblogs.asp.net/pjohnson/archive/2006/02/07/Convert.ChangeType-doesn_2700_t-handle-nullables.aspx

几年前编写了一个包装器来处理这个问题,但这也不是完美的。

http://weblogs.asp.net/pjohnson/archive/2006/02/07/Convert.ChangeType-doesn_2700_t-handle-nullables.aspx

或者你可以试试:

propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);

//But this will cause problems if your string value IsNullOrEmplty...

你可以使用Convert.ChangeType() -它允许你在任何IConvertible类型上使用运行时信息来更改表示格式。但是,并不是所有的转换都是可能的,如果您希望支持从非IConvertible类型转换,则可能需要编写特殊情况的逻辑。

相应的代码(没有异常处理或特殊情况逻辑)将是:

Ship ship = new Ship();
string value = "5.5";
PropertyInfo propertyInfo = ship.GetType().GetProperty("Latitude");
propertyInfo.SetValue(ship, Convert.ChangeType(value, propertyInfo.PropertyType), null);