小编典典

通过反射使用字符串值设置属性

c#

我想通过反射设置对象的属性,其值为type
string。因此,例如,假设我有一个Ship类,其属性为Latitude,它是一个double

这是我想做的:

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

照原样,这将引发ArgumentException

类型为“ System.String”的对象不能转换为类型为“ System.Double”。

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


阅读 388

收藏
2020-05-19

共1个答案

小编典典

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

相应的代码(无异常处理或特殊情况逻辑)为:

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